我创建了一个JFrame
,它在MigLayout
中包含一个JPanel
。
在这个布局中,我有5列和4行,每个列都有一个“大单元格”。
“大单元格”扩展JPanel
并具有边框颜色,在“大单元格”中是“小单元格”,它也扩展了JPanel
,并具有边框颜色。16x16网格内的大细胞的小细胞。
我试图画一幅图,但它只在画完其他东西(边框、背景等)之后才画出图像。
但是我想先画图像,然后再画边框。
我不能将setIcon用于单个单元格,因为它不能绘制图像(不确定为什么),而且它使我的网格更大,程序溢出得太大,甚至不适合4k分辨率。
这是一张什么样子的照片
我希望每一个黑色的‘盒子’或‘大细胞’有它自己的背景图像,这是绘制或渲染后的小细胞与橙色的边框。
这是这幅画的样子
你可能看不出来,但这是在每个“大单元格”中呈现的图像,就像它应该呈现的那样,除了它在所有事物的前面。它看起来只是一个图像,但不要被愚弄,因为它是一个无缝的图像。
这里是'BigCell‘类,我假设它是问题的根源。
package com.michaelgates.dev.OldLeaf.gui.components;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
public class BigCell extends JPanel
{
int column;
int row;
Cell[][] children;
JPanel parent;
Image image;
public BigCell(int column, int row, JPanel parent)
{
this.column = column;
this.row = row;
this.parent = parent;
setLayout(new GridLayout(16, 16, 0, 0));
setBorder(new LineBorder(Color.DARK_GRAY, 2));
children = new Cell[16][16];
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
{
Cell cell = new Cell(i, j, this);
add(cell);
children[i][j] = cell;
}
}
image = Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("img/acre/acre_0.png"));
}
@Override
public void paint(Graphics g)
{
if (image != null)
{
g.drawImage(image, 0, 0, (int) getSize().getWidth() - 0, (int) getSize().getHeight() - 0, this);
}
super.paint(g);
}
}
和“Cell”类,它是带有橙色边框的小盒子
package com.michaelgates.dev.OldLeaf.gui.components;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
public class Cell extends JPanel
{
int column;
int row;
BigCell parent;
public Cell(int column, int row, BigCell parent)
{
this.column = column;
this.row = row;
this.parent = parent;
setBorder(new LineBorder(Color.orange, 1));
//setBackground(Color.LIGHT_GRAY);
}
}
发布于 2015-10-23 06:05:39
改变...
@Override
public void paint(Graphics g)
{
if (image != null)
{
g.drawImage(image, 0, 0, (int) getSize().getWidth() - 0, (int) getSize().getHeight() - 0, this);
}
super.paint(g);
}
至
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, (int) getSize().getWidth() - 0, (int) getSize().getHeight() - 0, this);
}
}
paintComponent
是在paintBorder
和paintChildren
之前调用的,因此它是绘制背景图像的最佳位置
然后将setOpaque(false);
添加到Cell
的构造函数中。
看看表演定制绘画和AWT和Swing中的绘画,了解更多关于绘画如何在秋千上工作的细节。
https://stackoverflow.com/questions/33295580
复制相似问题