2014-03-28 34 views
0

我有以下的代碼,吸引了整個屏幕上的不可見的窗口:爲什麼在第二次調用繪畫時沒有任何東西被繪製到我的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的值,他們會得到正確的更新,所以我不知道爲什麼它沒有被繪製。有人知道我在這裏做錯了嗎?

感謝您的任何建議!

+0

不要阻塞EDT(Event Dispatch Thread) - 當發生這種情況時,GUI將「凍結」。而不是調用'Thread.sleep(n)'實現一個Swing'Timer'來重複任務。有關更多詳細信息,請參見[Swing中的併發](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。 –

+0

爲什麼選擇AWT而不是Swing?看到我對[Swing extras over AWT]的回答(http://stackoverflow.com/a/6255978/418556)有很多很好的理由放棄使用AWT組件。 –

回答

2

我是新來的,所以我可能是錯的。

  • 我認爲你的問題是關於如何使用Window對象而不是JPanel。所以把你的Window對象改爲JPanel。您可能應該使用JFrame來完成最後一個窗口。 你應該使用JPanel,我認爲你可以用來執行移動球的繪製方法是正確實現的。

  • 而不是重寫paint()方法,您需要重寫paintComponent()方法。 按照繪製對象的循環。

是這樣的...

  @Override 
      protected void paintComponent(Graphics g) { 
       super.paintComponent(g); 
       g.setColor(Color.ORANGE); 
       g.fillOval(x, y, CIRCLE_DIAMETER, CIRCLE_DIAMETER); 
      } 

的super.paintComponent方法()應空出JPanel的原始圖像,然後你應該能夠得出更新後的圖像。

這些可以幫助你和(我還沒有真正看着他們正確地):

Java ball moving

http://docs.oracle.com/javase/tutorial/uiswing/painting/

Java Bouncing Ball

很抱歉,如果我錯過了什麼。 (我還沒有測試過你的代碼)

相關問題