Dan*_*mer 2 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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
dur*_*597 10
Thread.sleep()给事件派遣线程!这会导致实际重绘屏幕的线程并使控件响应停止执行任何操作.
对于动画,请使用Timer.不要担心自己编写while循环,只告诉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
Run Code Online (Sandbox Code Playgroud)
private final Timer yourTimer;
public Graph() {
yourTimer = new Timer(2000, new TimerActionListener());
timer.start();
}
Run Code Online (Sandbox Code Playgroud)
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(0,0,x,y);
}
Run Code Online (Sandbox Code Playgroud)