[英]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();
}
}
}
}
Thread.sleep()
! 这会导致实际重绘屏幕的线程并使控件响应停止执行任何操作 。
对于动画,请使用Timer
。 不要担心自己编写while循环,只需告诉Timer
每Timer
触发一次,并在该计时器内更改x
和y
的值。 就像是:
// 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会给你的问题。
如果你想要一个动画,你可以:
使用挥杆计时器
在新线程中创建一个循环(而不是事件调度线程)。 你的循环看起来像这样:
如下:
while(running){
update();
render();
try(
Thread.sleep(1000/fps);
)catch(InterruptedException ie){
ie.printStackTrace();
}
}
注意:要为动画制作一个合适的循环,您需要的不止于此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.