[英]JComponent not drawing inside JPanel
Swing普通客戶的簡單問題。
這個想法是通過JComponent對象加載圖像並將其用作JPanel的背景。 當toString()
方法中的圖像信息正確加載且paintComponent()
方法正在運行時,似乎加載得很好,但是由於某種原因,它無法在JFrame內部正確呈現,從而導致空白幀。 這是代碼:
RicochetFrame.java
public class RicochetFrame extends JFrame {
RicochetStartPanel startPanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RicochetFrame window = new RicochetFrame();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public RicochetFrame() throws IOException {
startPanel = new RicochetStartPanel();
this.getContentPane().add(startPanel);
this.setBounds(0, 0, 500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.pack();
this.setVisible(true);
}
}
RicochetStartPanel.java
public class RicochetStartPanel extends JPanel {
RicochetStartPanel() throws IOException {
BufferedImage myImage = ImageIO.read(new File("frame_bg.jpg"));
this.add(new RicochetImagePanel(myImage));
this.setVisible(true);
this.validate();
this.repaint();
}
}
RicochetImagePanel.Java
public class RicochetImagePanel extends JComponent {
private Image image;
public RicochetImagePanel(Image image) {
this.setVisible(true);
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
您的RicochetImagePanel
自己調整為首選大小=> [0,0]。 重寫其getPreferredSize()
以返回圖像的尺寸(如果不為null)。 更好的是,為什么不簡單地在JLabel中將圖像顯示為ImageIcon?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.