2017-06-03 97 views
0

所以,我已經在java上學了一門AP課程,而在課堂上,我們從來沒有真正去過repaint(),以及如何正確使用它。我也通過互聯網搜索,並且我個人還沒有找到任何關於調用repaint()的標準方式的答案。我們是否應該調用main類的repaint()方法,如下所示?正確的重繪方法JComponent

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

public class RepaintExample{ 

    public static void main(String[] args){ 

     JFrame frame = new JFrame(); 
     JComponent component = new JComponent(); 
     frame.add(component); 
     frame.repaint(); 
    } 

} 

或者我稱之爲JComponent.repaint()像這樣

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

public class RepaintExample{ 

    public static void main(String[] args){ 

     JFrame frame = new JFrame(); 
     JComponent component = new JComponent(); 
     frame.add(component); 
     component.repaint(); 
    } 

} 

或者,有兩種方法都錯了,JComponent.repaint()應該從paintComponent被稱爲如下所示:

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

public class ComponentRepaintExample extends JComponent{ 

    public void paintComponent(Graphics g){ 

     //Draw stuff 
     for(int i = 0; i < 10; i++){ 
      //Draw stuff 
      this.repaint(); 
     } 
    } 

} 

這是這三種方法都是錯誤的。瞭解如何正確使用repaint()方法的任何幫助。整個話題對我來說都很籠統,所以如果我使用的術語不正確,我很抱歉。所有的提前感謝。

回答

2

爲什麼你認爲你需要調用repaint()?

當組件的屬性發生更改時,將由Swing組件自動調用repaint()方法。

例如,如果您有一個JLabel,並且您調用setText(...)setIcon(...),那麼這些方法將自動調用repaint()。

你永遠不會從繪畫方法調用repaint()。

如果您正在做自定義繪畫,那麼您的代碼應該像其他任何Swing組件一樣構造。那就是你爲你的自定義組件創建getter/setter方法來改變組件的屬性。在setter方法中,您調用repaint()。