2015-08-26 153 views
0

我剛開始學習GUI的和Swing,並決定寫一個程序我在一本教科書來顯示彩色矩形,使它看起來像它在減小尺寸在屏幕上找到。的Java Swing動畫的基本問題

下面是我寫的代碼,我的問題是,矩形在屏幕上顯示,但不重新粉刷,以更小的尺寸每隔50ms。任何人都可以指出我哪裏錯了?

非常感謝

import javax.swing.*; 
import java.awt.*; 

public class Animate { 

int x = 1; 
int y = 1; 

public static void main(String[] args){ 

    Animate gui = new Animate(); 
    gui.start(); 

} 

public void start(){ 

    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    Rectangles rectangles = new Rectangles(); 

    frame.getContentPane().add(rectangles); 
    frame.setSize(500,270); 
    frame.setVisible(true); 

    for(int i = 0; i < 100; i++,y++,x++){ 

     x++; 
     rectangles.repaint(); 

     try { 
      Thread.sleep(50); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 

    } 

} 





class Rectangles extends JPanel { 

public void paintComponent(Graphics g){ 
    g.setColor(Color.blue); 
    g.fillRect(x, y, 500-x*2, 250-y*2); 
} 

} 
} 
+0

你做任何基本的調試?你有沒有向你的paint方法添加一條語句來查看它是否被調用?你有沒有顯示x/y的值? – camickr

回答

2

矩形顯示器上屏幕,但沒有重新粉刷到每50ms更小的尺寸

當做自定義繪畫基本代碼應該是:

protected void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); // to clear the background 

    // add custom painting code 
} 

如果不清除,則古畫仍然是背景。所以畫更小的東西不會有所作爲。

對於你的代碼中x的更好的結構/ Y變量應該在Rectangles類中定義。那麼你應該創建一個像decreaseSize()的方法這也是在你的Rectangles類中定義。此代碼將更新x/y值,然後調用自身的重繪。所以你的動畫代碼只會調用decreaseSize()方法。

+0

現在完全合理,謝謝。我會嘗試創建你建議的方法 – user3650602

0
  1. 你應該重繪整個JFrame代替(或JPanel的圖形上)。
  2. 你不必調用x++兩次,而不是做x+=2

你的代碼改成這樣(的作品,我也是固定的縮進):

import javax.swing.*; 
import java.awt.*; 

public class Animate { 

    int x = 1; 
    int y = 1; 

    public static void main(String[] args) { 

     Animate gui = new Animate(); 
     gui.start(); 

    } 

    public void start() { 

     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     Rectangles rectangles = new Rectangles(); 

     frame.getContentPane().add(rectangles); 
     frame.setSize(500, 270); 
     frame.setVisible(true); 

     for (int i = 0; i < 100; i++, y++, x += 2) { 
      frame.repaint(); 

      try { 
       Thread.sleep(50); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
      } 
     } 

    } 

    class Rectangles extends JPanel { 

     public void paintComponent(Graphics g) { 
      g.setColor(Color.blue); 
      g.fillRect(x, y, 500 - x * 2, 250 - y * 2); 
     } 

    } 
} 
+0

1)沒有理由重新繪製整個框架。如果只有面板改變,那麼只需重新繪製面板。 2)很好的建議,但是發佈的代碼不在EDT上執行。從主方法執行的代碼在普通線程UNLESS上調用,代碼被封裝在一個'SwingUtilities.invokeLater(...)'中。 – camickr

+0

@camickr他沒有創造一個JPanel,他說一切JFrame的contentPane中。 (但是謝謝你指出我的陳述是不正確的(對第2點也是一樣))。 –