2014-03-12 36 views
0

我想將一個對象添加到JPanel,然後在重新限制JPanel並添加新對象之後重新繪製一個對象。如何正確添加組件並用組件重新繪製JPanel?

package papProject; 

import java.awt.BorderLayout; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

@SuppressWarnings("serial") 
public class Animation extends JPanel{ 

    private static boolean loop = true; 
    private static int frameTimeInMillis = 10; 

public static void main(String[] args){ 
     JPanel Ani = new JPanel(); 
     Ani.getParent(); 
     setup(Ani); 

     while (loop) { 

       Ani.repaint(); 

       try { 
        Thread.sleep(frameTimeInMillis); 
       } catch (InterruptedException e) { 
       } 
      } 
     } 

public static void setup(JPanel Panel) 
{ 
     Circle circle[] = new Circle[10]; 
     JFrame jf = new JFrame(); 

     jf.setTitle("Falling Shapes Animation"); 
     Panel.setLayout(new BorderLayout()); 
     jf.setSize(600,400); 
     jf.setVisible(true); 
     jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     jf.getContentPane().add(Panel); 

     for(int i = 0; i < circle.length; i++) 
     { 
      Panel.add(circle[i] = new Circle()); 
     } 
    } 
} 

此代碼繪製JPanels和圓對象添加到它,並假定重繪該組件,然後添加新的對象。我相信我的問題是與main()方法。

@SuppressWarnings("serial") 
public class Circle extends Animation implements ActionListener 
{ 

    int ranNum = 0; 
    int y = 0; 
    int x = (int) Math.random(); 
    int velY = 2; 

    Circle() 
    { 
     x = getRanNum(); 
    } 

    public int getRanNum() { 
     Random rand = new Random(); 
     for (int j = 0; j<10; j++)   
     ranNum = rand.nextInt(300); 
     return ranNum; 
     } 

    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 

     g.setColor(Color.RED); 
     g.fillOval(x, y, 30, 30); 

    } 

    public void actionPerformed(ActionEvent e) 
    { 
     if (y>370){ 

     velY =-velY; 

    } 
     y = y + velY; 
    } 

} 

此代碼從隨機的x位置繪製Cirlce對象並將其移動到y方向。 感謝您給予的任何幫助。

回答

0

看起來您正在調用EDT(Event Dispatching Thread)中的所有內容。 如果然後使用類似

while (loop) { 
      Ani.repaint(); 
      try { 
       Thread.sleep(frameTimeInMillis); 
      } catch (InterruptedException e) { 
      } 
     } 
    } 

這實際上阻止您的線程,你也不會看到任何東西。爲您的動畫更好地創建一個新的ThreadRunnable,然後開始新線程。

0

我不確定,但在主要方法中,重新繪製JPanel而不是顯示窗口的JFrame。我留下了一個代碼示例,我在其中重繪了JFrame和cirlce!

@SuppressWarnings("serial") 
public class Animation extends JPanel{ 

    private static boolean loop = true; 
    private static int frameTimeInMillis = 100; 
    static JFrame jf; 

public static void main(String[] args){ 
    JPanel Ani = new JPanel(); 
    Ani.getParent(); 
    setup(Ani); 
    jf = new JFrame(); 

    while (loop) { 

     jf.add(new Circle()); 
     jf.repaint(); 
     jf.setVisible(true); 

      try { 
       Thread.sleep(frameTimeInMillis); 
      } catch (InterruptedException e) { 
      } 
     } 
    } 
+0

我加了'jf = new JFrame();',否則會拋出一個空點異常。 – reporter

+0

這是正確的,因爲我沒有放置整個代碼,所以我在方法「setup」中放入了「jf = new JFrame()」。謝謝。 – zicrox