我有下面这个 JFrame:
public class TestJFrame extends JFrame {
public RecyclingMachinesGui(String title) {
super (title);
Container container = getContentPane();
container.setLayout(new FlowLayout());
Panel r = new Panel();
Jbutton j = new JButton("Recycle Item");
r.add(j);
container.add(r);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(500,500);
setVisible(true);
}
private class Panel extends JPanel {
private BufferedImage image;
public Panel() {
try {
image = ImageIO.read(new File("./temp.png"));
}catch (IOException e) {
e.getMessage().toString();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
}
在我的主方法的上述代码中,当我出于某种原因运行 new TestJFrame()
时,我只在 Panel
中看到 JButton j
> (我将其添加到容器中)并且在面板内看不到图像。我的Panel中的paintComponent
方法没有被调用吗?
我想在面板的顶部有一个图片,在底部有一个按钮。谁能解释为什么这种情况没有发生?
最佳答案
Panel
中的图像未显示,
因为Panel
没有合适的首选尺寸。
因此 LayoutManager(FlowLayout
)不知道哪个尺寸
给面板,并给它一个非常小的正方形的大小。
因此,您的 Panel
的 paintComponent
实际上被调用,
但它只在一个看不见的小区域上绘画,
您可以在 Panel
的构造函数中轻松修复它,
加载图像后立即调用 setPreferredSize
:
image = ImageIO.read(new File("./temp.png"));
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
关于java - 将图像和按钮添加到 JPanel 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42428711/