2012-03-04 66 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