我具有低於此的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。 –