2012-06-15 44 views
3

可能重复:
How to make an animation with Swing?重新绘制在for循环

在摆动,我数组排序,并希望制作动画。每次我在一个循环中更新数组,我有另一个while循环暂停效果,当我打电话repaint()实际上没有调用。为什么它不起作用? Thread.sleep(1000);冻结应用程序并不会恢复。

public class Shape extends JPanel { 

    private static final long serialVersionUID = 1L; 
    public int col; 
    public JButton b2 = new JButton("Sort"); 
    public Rectangle2D.Double table = null; 
    public ArrayList<Integer> arr = null; 

    public Shape(){ 

     initArray(); // initialize array with random number of random numbers 
     table = new Rectangle2D.Double(10,10,400,400); 
     add(b2); // button sort 

     b2.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
          System.out.println("sort it!"); 
          Sort(arr); 
          display(arr); 
        } 
     }); 
    } 

    public void initArray() { 
     col = generateRandom(10,20);   // generate a random number of bars 10 - 20 
     arr = new ArrayList<Integer>(col); 

     for(int i = 0; i < col; i++){ 
       // for each bar generate a random height 10 - 300 
       int h = generateRandom(10, 390); 
       arr.add(h); 
     } 
    } 


    public void paintComponent(Graphics g){ 
     System.out.println("check"); 
     clear(g); 
     Graphics2D g2d = (Graphics2D)g; 
     System.out.println(arr.size()); 
     for(int j = 0; j < arr.size(); j++) { 
       g2d.drawRect(j*20+20,410-arr.get(j),20,arr.get(j)); 
     } 
    } 

    protected void clear(Graphics g){ 
     super.paintComponent(g); 
    } 

    /* 
    * generate random number in the range from 1 to 400 
    */ 
    private int generateRandom(int start, int end){ 
     return new Random().nextInt(end)+start; 
    } 

    public void Sort(ArrayList<Integer> arr) { 
     int t = 0; 

     boolean swap = true; 
     do { 
       swap = false; 
       for(int i = 0; i < arr.size() - 1; i++) { 
         if(arr.get(i).compareTo(arr.get(i+1)) > 0) { 
           int temp = arr.get(i); 
           arr.set(i, arr.get(i+1)); 
           arr.set(i+1, temp); 
           swap = true; 
           // iterate to make effect of pausing 
           while(t < 100) {display(arr);t++;} 
           t = 0; 
           // repaint array 
           repaint(); 
         } 
       } 
     } while(swap); 
    } 

    static void display(ArrayList<Integer> arr) { 
     for(int i = 0; i < arr.size()-1; i++) 
       System.out.print(arr.get(i) + ", "); 
     System.out.println(arr.get(arr.size()-1)); 
    } 

    public static void main(String[] arg){ 
     WindowUtilities.openInJFrame(new Shape(), 500,500); 
    } 
} 
+0

请你看看这个【答案】(http://stackoverflow.com/questions/10338163/paintcomponent-does-not如果它是通过递归函数调用的/ 10352884#10352884)。这个答案的开始可以给你一个公正的判断,至于为什么你的重绘没有被调用(虽然只有队列中的第一个repaint()被调用,而其余的被丢弃)。这个答案也说明了这种情况,如果有人想在一个循环内重绘,那么该如何绘制,虽然这种方法不经常使用,因此附加了一些字符串。 –

回答

7

不要使用Thread.sleep作为Swing,因为它会阻止用户界面。改为使用javax.swing.Timer:每次计时器触发动作侦听器时,都会更新阵列并安排重新绘制。这将为您提供动画效果。

又见