2015-08-26 155 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点也是一样))。 –