2013-01-05 147 views
1

的那個應該消息不被打印。我有一個印象,即不調用繪畫方法。如果不是,爲什麼不呢?爲什麼不調用paintComponent方法?在printComponent方法要打印

import java.util.*; 
import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.io.*; 
import javax.swing.*; 
import javax.imageio.*; 

public class Main extends JFrame{ 
    CustomComponent cc; 

    public static void main(String[] args) { 
     Main m = new Main(); 
    } 

    public Main(){ 
     setTitle("Diverse Testari 7"); 
     setLayout(null); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setSize(600, 400); 

     cc = new CustomComponent(); 
     cc.setImage("rgbcmy.jpg"); 

     add(cc); 
     pack(); 
     setVisible(true); 
    } 
} 

class CustomComponent extends JPanel{ 
    BufferedImage img = null; 
    public void setImage(String str){ 
    try { 
     img = ImageIO.read(new File(str)); 
     System.out.println("SUCCESS!"); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     // TODO Auto-generated method stub 
     System.out.println("altceva"); 
     super.paintComponent(g); 
     System.out.println("ceva"); 
    } 
} 

回答

2

Main構造函數添加以下代碼:

new Thread(new Runnable() { 
    public void run() { 
     repaint(); 
     try { 
      Thread.sleep(20); 
     } catch (InterruptedException e) {} 
    } 
}).start(); 

paintComponent纔會被調用時,你repaint();

而且,永遠永遠永遠使用setLayout(null);。請參閱here

此代碼將不斷重繪面板,所以它會不斷地調用paintComponent。這很好,因爲它會始終保持面板更新。當您更改面板中的內容時,您也可以致電repaint();

+0

如果我重畫後,我設定的框架可見? –

+0

@ AndrewG.H。是的,那樣做。 – Doorknob

+0

我的意思是,沒有使用你的線程。 –

相關問題