[英]Why is my Drawing panel, sometimes painting and other time not, on window resize?
[英]Why is there no Picture in my Panel/Window?
我的代碼有什么問題? 我只想在我的 Window 中有一張圖片...
//class ImagePanel:
public class ImagePanel extends JPanel {
private static final long serialVersionUID = -7664761101121497912L;
public Image i;
public ImagePanel(Image i) {
this.i = i;
}
@Override
public void paintComponents(Graphics g) {
super.paintComponent(g);
g.drawImage(this.i, 0, 0, null);
}
}
//class Main
public class Main extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImagePanel panel = null;
try {
panel = new ImagePanel(ImageIO.read(new File("D:/test.JPG")));
} catch (IOException e) {
e.printStackTrace();
}
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
只有一個沒有圖片的 Window :( 有什么問題?有沒有簡單的方法來設置 window == 圖片大小的大小?
謝謝!
您必須覆蓋paintComponent(Graphics g)
而不是paintComponent
s (Graphics g)
。
最好的解決方案是使用 JLabel。 不要重新發明輪子。 您無需進行自定義繪畫。
但是,如果您進行自定義繪畫,那么您需要將 getPreferredSize() 方法覆蓋為圖像的大小,以便布局管理器可以完成他們的工作。
我對 Java 窗格完全不熟悉,但是在將 ImagePanel 添加到內容窗格之前,您不需要設置它的大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.