我有以下的代碼,吸引了整個屏幕上的不可見的窗口:爲什麼在第二次調用繪畫時沒有任何東西被繪製到我的awt窗口?
Window w=new Window(null)
{
private int x = 200; private int y=200;
private int dx = 2; private int dy = 2;
private final int CIRCLE_DIAMETER = 400;
@Override
public void paint(Graphics g)
{
g.setColor(Color.ORANGE);
g.fillOval(x, y, CIRCLE_DIAMETER, CIRCLE_DIAMETER);
}
@Override
public void update(Graphics g)
{
if(x<=0)
dx*=-1;
if(y<=0)
dy*=-1;
if(x+CIRCLE_DIAMETER>=this.getWidth())
dx*=-1;
if(y+CIRCLE_DIAMETER>=this.getHeight())
dy*=-1;
x+=dx;
y+=dy;
this.paint(g);
}
};
w.setAlwaysOnTop(true);
w.setBounds(w.getGraphicsConfiguration().getBounds());
w.setBackground(new Color(0, true));
w.setVisible(true);
//Lazy way of making calls to paint for testing
while(true){
w.repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
此畫在座標x和y在屏幕上的橙色的圓。當我在無限循環中調用repaint時,paint會被調用,x和y會更新,但圓圈永遠不會被繪製到另一個位置。如果我在每次調用paint時都打印x和y的值,他們會得到正確的更新,所以我不知道爲什麼它沒有被繪製。有人知道我在這裏做錯了嗎?
感謝您的任何建議!
不要阻塞EDT(Event Dispatch Thread) - 當發生這種情況時,GUI將「凍結」。而不是調用'Thread.sleep(n)'實現一個Swing'Timer'來重複任務。有關更多詳細信息,請參見[Swing中的併發](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。 –
爲什麼選擇AWT而不是Swing?看到我對[Swing extras over AWT]的回答(http://stackoverflow.com/a/6255978/418556)有很多很好的理由放棄使用AWT組件。 –