我对以下一段代码有疑问:照片没有显示在我的JFrame
...中
请帮帮我。
public class ImageRead extends JFrame {
JPanel pan;
Image img1;
public ImageRead() throws IOException {
this.pan = new JPanel();
final Dimension d = new Dimension(500, 500);
this.img1 = ImageIO.read(new File("C:\\Users\\KHALED\\workspace\\"
+ "Universite Base De Donner\\src\\2.jpg"));
this.pan.setPreferredSize(d);
this.pan.add(new JButton("entre"));
this.pan.setBackground(Color.red);
this.getContentPane().add(this.pan);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setSize(500, 500);
this.setVisible(true);
this.setResizable(false);
}
public void paintComponents(final Graphics g) {
final Graphics2D g2 = (Graphics2D) g;
g.drawImage(this.img1, 0, 0, this.pan);
g2.finalize();
}
public static void main(final String[] args) throws IOException {
new ImageRead();
}
}
答案 0 :(得分:0)
这有很多问题,但可能主要的一点是你不想覆盖JFrame的paintComponent,你想在ContentPane上做到这一点。所以创建一个JPanel派生类,并在那里执行该代码,然后调用myframe.setContentPane(mypanel);
另一个问题是你不想在g2上调用finalize()
您可能希望使用类路径资源来加载该图像,而不是使用File io。
答案 1 :(得分:0)
您应该使用正确的布局和真正的ImageIcon。另外,您的意思是destroy();
而不是g2.finalize();
吗?