2015-06-28 78 views
1

我是一個很初級,所以我覺得我在做愚蠢的錯誤,但我有:的paintComponent裏面功能

public class Draw extends JPanel { 

    private static final long serialVersionUID = 1L; 

    public Draw(int rx, int ry) 
    { 

     public void paintComponent(Graphics g) 
     { 
      super.paintComponent(g); 
      this.setBackground(Color.WHITE); 
      g.setColor(Color.BLUE); 
      try{ 
       g.fillRect(rx, ry, 5, 5); 
       Thread.sleep(1000); 
      } 
      catch(InterruptedException ex) 
      { 
       Thread.currentThread().interrupt(); 
      } 

     } 
    } 

    public static void main(String[] args) { 
     JFrame f = new JFrame("Title"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     for (int i = 1; i < 40; i++) { 
      Random r = new Random(); 
      int rx = r.nextInt(40); 
      int ry = r.nextInt(40); 

      Draw d = new Draw(rx, ry); 
      f.add(d); 
      f.setSize(400, 400); 
      f.setVisible(true); 
     } 
    } 
} 

我想要的代碼來生成與每個環路一些延遲的隨機位置的矩形。 Java寫道:「void是變量paintComponent的無效類型」。我不相信這一點,因爲如果我把PaintComponent放在Draw函數外面,它可以工作(但不是我不想讓他工作)。 PaintComponent不能在其他函數內部或有其他錯誤嗎?

+0

將該方法置於構造函數之外。 – Maroun

回答

1

這裏是你想要的一個例子:

你不應該定義內的其他方法,比如一個構造函數方法。如果只需要創建時間間隔,也不要使用線程。改爲使用javax.swing.Timer

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 

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

public class Draw extends JPanel { 

    private static final int FRAME_HEIGHT = 400; 

    private static final int FRAME_WIDTH = 400; 

    private static final int RECT_WIDTH = 40; 

    private static final int RECT_HEIGHT = 25; 


    private static final long serialVersionUID = 1L; 

    public Draw() 
    { 
     this.setBackground(Color.WHITE); 
    } 

    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     // 
     Graphics2D g2 = (Graphics2D) g; 
     g2.setColor(Color.BLUE); 

     Random r = new Random(); 
     int rx = r.nextInt(FRAME_WIDTH-RECT_WIDTH); 
     int ry = r.nextInt(FRAME_HEIGHT-RECT_HEIGHT); 
     g.fillRect(rx, ry, RECT_WIDTH, RECT_HEIGHT); 
    } 

    public static void main(String[] args) { 
     JFrame f = new JFrame("Title"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     final Draw d = new Draw(); 
     f.add(d); 
     f.setSize(FRAME_WIDTH, FRAME_HEIGHT); 
     f.setVisible(true); 

     Timer t = new Timer(1000, new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       d.repaint(); 
      } 
     }); 
     t.start(); 
    } 
} 

好運。