java这张照片没有显示在这张相框里吗?
我对下面的代码有一个问题:照片没有显示在我的JFrame
请帮帮我
我的Java代码:
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();
}
}
# 1 楼答案
这有很多问题,但可能主要的问题是,您不想覆盖JFrame的paintComponent,而是希望在ContentPane上这样做。因此,创建一个JPanel派生类,并在其中编写代码,然后调用myframe。setContentPane(mypanel)
另一个问题是您不想在g2上调用finalize()
您可能希望使用类路径资源来加载该映像,而不是使用文件io
# 2 楼答案
您可能应该使用正确的布局和真正的图像图标。还有,你是说
destroy();
而不是g2.finalize();