2014-11-24 46 views
0

當我實現接口時,有一個問題。執行接口方法

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

/** 
    An icon that has the shape of the planet Mars. 
*/ 
public class MarsIcon implements Icon 
{ 
    /** 
     Constructs a Mars icon of a given size. 
     @param aSize the size of the icon 
    */ 
    public MarsIcon(int aSize) 
    { 
     size = aSize; 
    } 

    public int getIconWidth() 
    { 
     return size; 
    } 

    public int getIconHeight() 
    { 
     return size; 
    } 

    public void paintIcon(Component c, Graphics g, int x, int y) 
    { 
     Graphics2D g2 = (Graphics2D) g; 
     Ellipse2D.Double planet = new Ellipse2D.Double(x, y, 
      size, size); 
     g2.setColor(Color.RED); 
     g2.fill(planet); 
    } 

    private int size; 
} 

    import javax.swing.*; 

public class IconTester 
{ 
    public static void main(String[] args) 
    { 
     JOptionPane.showMessageDialog(
      null, 
      "Hello, Car!", 
      "Message", 
      JOptionPane.INFORMATION_MESSAGE, 
      new MarsIcon(100)); 
     System.exit(0); 
    } 
}  

在IconTester中,我只創建一個MarsIcon(100)。我沒有打電話給方法。但似乎執行了paintIcon(;;;)。 怎麼回事?這些方法是否自動調用?

+1

當您嘗試顯示圖標時,會調用'paintIcon'。由於您正在顯示帶有該圖標的消息對話框,因此它將被調用。 – BackSlash 2014-11-24 09:13:41

+1

如果您已經調試並檢查了調用堆棧,您將會看到誰在調用'paintIcon'。 – Smutje 2014-11-24 09:14:24

回答

2

您不直接調用paintIcon方法,當組件是可見UI的一部分時,顯示管理器會發生這種情況。

這是它,因爲你將它添加到JOptionPane

+0

謝謝!得到它了 – user3199837 2014-11-24 09:17:52