java - 为什么我的 while 循环在 PaintComponent 中不起作用?

标签 java swing jpanel 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() !!!

这会导致线程实际重绘屏幕并使控件响应停止执行任何操作。

For animations, use a Timer 。不必担心自己编写 while 循环,只需告诉 Timer 每隔一段时间触发一次,并更改 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);
}

关于java - 为什么我的 while 循环在 PaintComponent 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172561/

相关文章:

java - 如何让用户知道特定关键字在句子中是哪个单词(例如,这是第三个单词)

java - 遵循传统(非中介)MVC模式的监听器放置

java - 如何使用 JDialog 类删除或隐藏父窗口

java - 反序列化多维数组GSON

java - 可以在 catch block 中访问 try block 内定义的标签吗?

java - 访问 ActionListener 类中的 Gui,使用计时器每 x 秒更新一次

java - ArrayList 中的图形

java - JViewport 不会为 JPanel 的派生类生成视口(viewport)

java - 如何获取鼠标指针相对于框架的位置

java - JComboBox动态更新值