簡體   English   中英

如何在創建時繪制JFrame?

[英]How to paint a JFrame at creation?

我正在嘗試將背景圖像繪制到我正在制作的生活模擬游戲的JFrame上。 這是我的代碼:

public class MainFrame extends JFrame  {
 //creates image variables
Image background;

 public MainFrame(int w, int h) {
    //creates new JFrame and sets some other properties
    super("Life Simulation");
    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(new Dimension(w,h));
    //creates images
    background = Toolkit.getDefaultToolkit().createImage("img/default.jpg");
    this.repaint();
    setVisible(true);
}
 @Override
 public void paint(Graphics g) {
         super.paint(g);
         Graphics2D g2d = (Graphics2D) g;
         g.drawImage(background,0,0,null);
     }
}

在設置可見之前,我嘗試過重新粉刷它,但是什么也沒有。 當我從主方法啟動程序時,JFrame只是空白。 但是,如果我稍稍調整大小,就會調用paint方法並繪制背景圖像。

這是我的主要方法:

public class Main {

public static void main(String[] args) {
    MainFrame frame = new MainFrame(1080,720);
    frame.repaint(); //tried invoking paint() here as well but again to no avail
}

}

編輯:我相信也值得一提的是,我以前很少或根本沒有使用paint()或其任何變體的經驗,只知道應如何實現及其功能。

哦,我想強調在調用drawImage方法時提供適當的ImageObserver對象的重要性。 而不是傳遞的null ,我建議你通過this

g.drawImage(background, 0, 0, this);

您可以了解通過Toolkit.createImage異步加載圖像時指定ImageObserver重要性

另外:盡管未為JFrame定義paintComponent ,但我還是建議避免重寫JFrame的paint方法。 相反,您可以創建一個可重用的ImagePanel類,或者僅使用一個匿名類,然后使用該類來設置JFrame的內容窗格。

這是ImagePanel類的示例:

class ImagePanel extends JPanel {
    private Image image;

    public ImagePanel(Image image) {
        this.image = image;
    }

    @Override protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

或者,如果您更喜歡匿名課程:

setContentPane(new JPanel() {
    @Override protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM