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?