2012-03-04 68 views
3

我想我需要把一些代码放在评论的地方(或者可能使用非静态方法,但我不确定)。主要方法创建窗口,然后启动图形方法。我想要蓝色方块闪烁。如何重新运行paint方法以使JPanel动画?

import java.awt.Color; 
import java.awt.Graphics; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 


public class paintTest extends JPanel{ 
private static JFrame theWindow = new JFrame("Window"); 
static boolean blueSqr = false; 

public void paint(Graphics g) { 
    g.setColor(Color.RED); 
    g.fillRect(10, 10, 10, 10); 

    if(blueSqr){ 
     g.setColor(Color.BLUE); 
     g.fillRect(10, 10, 10, 10); 
    } 
} 

public static void main(String[] args){ 
    createWindow(); 
    theWindow.getContentPane().add(new paintTest()); 
    while(true){ 
     blueSqr = false; 

     System.out.println("off"); 

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

     blueSqr = true; 
     // Needs something here 
     System.out.println("on"); 

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

public static void createWindow(){ 
    theWindow.setSize(500, 500); 
    theWindow.setLocationRelativeTo(null); 
    theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    theWindow.setVisible(true); 
} 
} 

任何帮助将是非常好的。

+2

它被称为 “法” 而不是 “空白”。 – 2012-03-04 09:17:55

回答

5

使用摇摆Timer致电repaint()。此外,覆盖paintComponent()JPanel,而不是paint()

事情是这样的:

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

public class PaintTest extends JPanel{ 

    boolean blueSqr = false; 

    PaintTest() { 
     setPreferredSize(new Dimension(100,25)); 
     ActionListener al = new ActionListener() { 
      public void actionPerformed(ActionEvent ae) { 
       blueSqr = !blueSqr; 
       repaint(); 
      } 
     }; 
     Timer timer = new Timer(1000,al); 
     timer.start(); 
    } 

    public void paintComponent(Graphics g) { 
     Color c = (blueSqr ? Color.BLUE : Color.RED); 
     g.setColor(c); 
     g.fillRect(10, 10, 10, 10); 
    } 

    public static void main(String[] args){ 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       JFrame theWindow = new JFrame("Window"); 
       theWindow.getContentPane().add(new PaintTest()); 
       createWindow(theWindow); 
      } 
     }); 
    } 

    public static void createWindow(JFrame theWindow){ 
     theWindow.pack(); 
     theWindow.setLocationByPlatform(true); 
     theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     theWindow.setVisible(true); 
    } 
} 

还有其他改进我不能打扰文档化(代码比言语更响亮说话)。如果您有任何问题(先查看文档,然后)问。

+1

非常感谢。 – twilding 2012-03-04 19:06:24

+0

不客气。 :)发布易于使用的代码。 – 2012-03-04 19:18:31

4

您的问题通过调用在Swing相关的代码Thread.sleep(int)

1),从来没有做到这一点,在摇摆延迟(有许多关于为什么不使用的编程语言睡眠的话题......)使用Swing Timer

2)你的JPanel不返回任何XxxSize

3)为Swing使用paintComponent(),只有当你已经得到了真正的重要原因,然后使用方法paint()更多关于重画和动画中的图形2D Graphics tutorial

4)Swing GUI的应建在Event Dispatch Thread