簡體   English   中英

什么是JPanel / Graphics方法paintComponent?

[英]What is the JPanel/Graphics method paintComponent?

所以我正在嘗試學習Java圖形,這些代碼讓我感到困惑。 我不明白這里有幾件事:

  1. 為什么paintComponenet使用了兩次方法的名稱,因為我們從super( JPanel )調用一個方法?
  2. 什么是Graphics g ,它不僅僅是Graphics對象的引用變量,因為我們沒有將它設置為= new Graphics();
  3. 為什么我的類中的方法名必須是paintComponent來調用JPanel或super中的方法paintComponent
  4. 我的類paintComponent的方法獲取Graphics對象的參數,但是什么時候paintComponent甚至被調用,什么時候插入Graphics的參數?

基本上我需要有人向我解釋這段代碼。

//note this is all in a class that extends JPanel, my JPanel is later placed in 
//a JFrame which is run through main
 public void paintComponent(Graphics g) 
        {
            int width = getWidth();             
            int height = getHeight();         

            super.paintComponent(g);   

            g.setColor(Color.RED);
            g.fillRect(10, 10, 200, 200); 
            g.setColor(Color.BLUE);
            g.drawRect(10, 10, 200, 200); 
        }

為什么paintComponenet使用了兩次,方法的名稱和我們從super調用的方法(JPannel)

它沒有被“使用”兩次。 它被覆蓋了一次,但你想調用父(JPanel)類的超級方法,這樣你就可以確保它自己做了一些內務畫,包括繪制它的子節點並清除屏幕上的任何臟位。

什么是Graphics g,它不僅僅是Graphics對象的引用變量,因為我們沒有將它設置為= new Graphics();

這是一個Graphics 參數 您沒有設置它= new Graphics()因為JVM會為您執行此操作。 它在需要時調用幕后方法,並提供參數。

為什么我的類中的方法名必須是paintComponent來調用JPannel或super中的方法paintComponent

它必須覆蓋super的方法,以便JVM在想要繪制GUI時調用正確的方法。

我的類paintComponent中的方法獲取Graphics對象的參數,但是什么時候paintComponent甚至被調用,什么時候插入Graphics的參數。

同樣,當您的程序要重新繪制GUI時,JVM會調用它,例如當您調用repaint()或操作系統想要重新繪制窗口時,例如窗口是否已最小化並恢復。

你真的很想閱讀圖形教程:

1)為什么paintComponenet使用了兩次,作為方法的名稱,我們稱之為super(JPannel)的方法

這里的行super.paintComponent(...),意味着我們希望JPanel首先以通常的Java方式繪制(這通常取決於所述JComponent的opaque屬性,如果它是真的,那么它就成了部分的責任程序員用完全不透明的顏色填充內容區域。如果是假的,那么程序員可以自由地保持不變。所以為了克服與這個合同相關的麻煩,使用了super.paintComponent(g),因為它遵守規則,並執行相同的任務,具體取決於opaque屬性是true還是false。

2)什么是Graphics g,它不僅僅是Graphics對象的引用變量,因為我們沒有將它設置為= new Graphics(); 4)我的類paintComponent中的方法獲取Graphics對象的參數但是paintComponent什么時候被調用,什么時候插入Graphics的參數

paintComponent方法是放置所有繪制代碼​​的地方。 確實,當需要繪制時會調用此方法,但繪制實際上從類層次開始更高,使用paint方法(由java.awt.Component定義。)此方法將由繪制子系統執行。你需要渲染組件。 它的簽名是:

public void paint(Graphics g)

javax.swing.JComponent擴展了這個類,並進一步將paint方法分解為三個單獨的方法,這些方法按以下順序調用:

protected void paintComponent(Graphics g)
protected void paintBorder(Graphics g)
protected void paintChildren(Graphics g)

API不會阻止您的代碼覆蓋paintBorder和paintChildren,但一般來說,沒有理由這樣做。 出於所有實際目的,paintComponent將是您需要覆蓋的唯一方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM