当我尝试使用 myCustomPanel.add(someComponent)
时,它不会添加...
这是我的自定义 JPanel 类:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
/**
*
* @author Jacob
*/
public class OSXMainPanel extends JPanel {
public static final long serialVersionUID = 24362462L;
private Image image;
public OSXMainPanel() {
super.setOpaque(true);
try {
image = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("/assets/background.png"), "background.png"));
} catch (Exception e) {}
}
@Override
protected void paintComponent(Graphics g) {
if (isOpaque())
{
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
for(int w = 0; w < this.getWidth(); w = w + 50) {
for(int h = 0; h < this.getHeight(); h = h + 50) {
g.drawImage(image, w, h, 50, 50, this);
}
}
}
}
最佳答案
这不起作用的原因是你的paintComponent方法没有绘制添加的组件。在 PaintComponent 方法开始时调用 super.paintComponent(g) 应该可以解决这个问题。
关于java - 无法将项目添加到自定义绘制的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4408312/