簡體   English   中英

paintComponent方法未繪制圖像

[英]paintComponent method is not drawing image

在將它合並到程序中之前,我試圖習慣使用paintComponent()方法。 但是,每當我嘗試將圖像繪制到JPanel ,它都無法正常工作。 我把代碼放在下面。 任何幫助,將不勝感激。 謝謝。

public class ExperimentGame extends JPanel{

Image image;

public ExperimentGame(){
    JFrame frame = new JFrame();
    SwingUtilities.isEventDispatchThread();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(this);
    frame.pack();
    frame.setSize(500,500); //my edit
    this.setBackground(Color.WHITE);
    frame.setVisible(true);
    try {
        image = ImageIO.read(this.getClass().getResource("spaceship (0).png"));
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(image, 50, 50, null);
}
}

public class ExperimentMain {

public static void main(String[] args) {
    ExperimentGame game = new ExperimentGame();
}
}

解決您的問題的一個小技巧是在構造函數的底部進行調用。

this.revalidate();
this.repaint();

但是,我建議您看看每當模型中發生更改時,如何使用Model-View-Controller更新視圖。 一個例子可以在這里找到。

暫無
暫無

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

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