我具有低于此的JFrame:添加图像和按钮到一个JPanel
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()
我只看到里面的JButton j
我Panel
(其我添加到我的容器中),并没有看到面板内的图像。我的面板中的paintComponent
方法没有被调用?
我想在顶部有一张图片,面板底部有一个按钮。任何人都可以解释为什么这不会发生?
是被载入图像,这是伟大?如果要在顶部显示图像并在面板上显示按钮,请使用“BorderLayout”,将图像包装在“JLabel”中并将其添加到中心位置,并将按钮向南放置到位置 – MadProgrammer
使用“面板类? – CapturedTree
应用程序资源在部署时将成为嵌入式资源,所以现在开始访问它们是明智的做法。 [tag:embedded-resource]必须通过URL而不是文件访问。请参阅[信息。页面为嵌入式资源](http://stackoverflow.com/tags/embedded-resource/info)如何形成的URL。 –