2013-03-31 36 views
0

以下代碼將一個按鈕放置在面板上。但有一個問題。我沒有看到按鈕上的標籤Click Me,也沒有看到在​​上畫的按鈕。這是爲什麼 ?我既沒有看到按鈕上的標籤,也沒有看到它塗成綠色。這是爲什麼 ?

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

class Tester extends JButton { 

     public Tester(String label) { 
      super(label); 
     } 

     @Override 
     public void paintComponent(Graphics g) { 
      g.setColor(Color.GREEN); 
     } 

     public static void main(String args[]) { 
      JFrame fr = new JFrame(); 
      JPanel p = new JPanel(); 
      JButton button = new Tester("Click Me !"); 
      p.add(button); 
      fr.add(p); 
      fr.setVisible(true); 
      fr.setSize(400,400);  
      fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     } 
} 
+0

請勿重寫組件的paintComponent()方法以更改顏色。相反,你應該調用'setBackground(...)'方法。 – camickr

回答

2

你需要調用

super.paintComponent(g); 

這將油漆所有子組件。然而,這裏不需要自定義繪畫,因爲JButton提供了一種方法setBackground來直接設置背景顏色。您可以使用

button.setBackground(Color.GREEN); 

參見:Performing Custom Painting

+0

這個電話意味着什麼?請您詳細說明一下 –

+0

它用於設置組件的背景顏色。沒有必要在這裏重寫'JButton'來給你這個功能 – Reimeus

+0

另外我正在測試其他需要自定義繪畫的東西 –

-1

首先,你需要撥打:super.paintComponent方法(G);在paintComponent()中,如果你想覆蓋它的任何行爲。但是,如果你只想改變背景顏色,那就在你的構造函數中做。沒有必要爲屬性更改重寫paintComponent。

+0

-1,Reimeus的回覆說要調用super.paintComponent()。我的評論說你應該使用setBackground(...)。無需重複建議。 – camickr

相關問題