簡體   English   中英

為什么我的while循環不能在paintComponent中工作?

[英]Why is my while loop not working in paintComponent?

當我運行此代碼時,我只看到一個空白(白色)面板,我想知道原因。

這是我的代碼:

Graph.java

public class Graph extends JPanel {
    private static final long serialVersionUID = -397959590385297067L;
    int screen=-1;
    int x=10;
    int y=10;
    int dx=1;
    int dy=1;       
    boolean shouldrun=true;
    imageStream imget=new imageStream();

        protected void Loader(Graphics g){

            g.setColor(Color.black);
            g.fillRect(0,0,x,y);
            x=x+1;
            y=y+2;

        }


        @Override
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
                while(shouldrun){
                    Loader(g);   
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }    
                }   
        }
}

不要在Event Dispatch Thread上調用Thread.sleep()

這會導致實際重繪屏幕的線程並使控件響應停止執行任何操作

對於動畫,請使用Timer 不要擔心自己編寫while循環,只需告訴TimerTimer觸發一次,並在該計時器內更改xy的值。 就像是:

// this is an **inner** class of Graph
public class TimerActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        x += dx;
        y += dy;
    }
}

// snip
private final Timer yourTimer;

public Graph() {
    yourTimer = new Timer(2000, new TimerActionListener());
    timer.start();
}
@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setColor(Color.black);
    g.fillRect(0,0,x,y);
}

你永遠不會在循環中改變shouldrun的狀態 - 所以它永遠不會結束。

此外,永遠不要在繪畫方法中調用Thread.sleep(...) 這種方法用於繪畫,永遠不會入睡,否則GUI將被置於睡眠狀態,將被凍結。

首先,paintComponent方法應該只處理所有繪畫而不處理任何其他內容(如果可能)。 您不應該在paintComponent中實現您的程序循環。

空白屏幕可能由多種原因引起。 您可以通過注釋掉代碼的某些部分並運行它來輕松地手動調試它。 看它是否仍然是空白的。

至少從我在這里看到的,你的paintComponent會給你的問題。

如果你想要一個動畫,你可以:

  1. 使用揮桿計時器

  2. 在新線程中創建一個循環(而不是事件調度線程)。 你的循環看起來像這樣:

如下:

while(running){
    update();
    render();
    try(
        Thread.sleep(1000/fps);
    )catch(InterruptedException ie){
        ie.printStackTrace();
    }
}

注意:要為動畫制作一個合適的循環,您需要的不止於此。

暫無
暫無

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

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