2015-04-05 101 views
1

Bascially我遇到了繪製我自定義組件的問題。每當調用repaint()時,我的Button類的paintComponent()被調用,但是在我的框架中沒有任何東西顯示出來。我也知道這個組件是合適的尺寸,並且位於正確的位置,因爲我設置了一個邊框來檢查它。PaintComponent()被調用,但未被繪製的JComponent

以下是我的自定義組件類:

public class Button extends JComponent { 

protected static final Color BUTTON_COLOR = Color.black; 
protected Point position; 
protected Dimension size; 

public Button(int posX, int posY, int width, int height) { 
    super(); 
    position = new Point(posX, posY); 
    size = new Dimension(width, height); 
    setBounds(position.x, position.y, size.width, size.height); 
    setBorder(BorderFactory.createTitledBorder("Test")); 
    setOpaque(true); 
} 

@Override 
protected void paintComponent(Graphics g) { 
    setBounds(position.x, position.y, size.width, size.height); 
    drawButton(g); 
    super.paintComponent(g); 
} 

@Override 
public Dimension getPreferredSize() { 
    return size; 
} 

public void drawButton(Graphics g) { 

    selectColor(g, BUTTON_COLOR); 
    g.fillRect(position.x, position.y, size.width, size.height); 
    g.setColor(Color.black); 
    g.drawRect(position.x, position.y, size.width, size.height); 

}} 

這是我的自定義組件將被添加到JPanel中:

public class MainMenu extends JPanel { 
public MainMenu() { 
    setBackground(Color.BLACK); 
    setLocation(0,0); 
    setPreferredSize(new Dimension(800,600)); 
    setDoubleBuffered(true); 
    setVisible(true); 
    this.setFocusable(true); 
    this.requestFocus(); 
}} 

最後,我想補充以下組件集成到一個MainMenu的JPanel :

main_menu.add(new Button(200, 200, 150, 50)); 
    dropdown = new JComboBox<File>() { 
     @Override 
     public void paintComponent(Graphics g) { 
      dropdown.setLocation(new Point(400, 200)); 
      super.paintComponent(g); 
     } 
    }; 

    main_menu.add(dropdown); 

有什麼奇怪的是,當repaint()在main_菜單中,即使Button的paintComponent()被調用,JComboBox也被繪製,但不是Button。

回答

3

幾個問題:

  • 你不應該繪畫方法中調用setBounds(...)paintComponent。此方法僅用於繪畫和繪畫。
  • 你的邊界和你的繪畫區域是相同的 - 但它們代表了兩個完全不同的東西。邊界是組件相對於其容器的位置,繪畫x,y是相對於JComponent本身的。所以你正在畫出你的界限。
  • 所以同樣,你drawButton方法應該是在0繪畫,0:g.drawRect(0, 0, size.width, size.height);
  • setBounds不應該被稱爲無關。這是佈局經理的工作。通過這樣做,您可以添加一整層潛力並且很難找到錯誤。
  • 我會覆蓋getPreferredSize()來幫助設置組件的最佳尺寸(編輯 - 儘管以非常簡單的方式,您已經這麼做了)。
  • 您不應該在按鈕內設置按鈕的位置 - 同樣,這是它的容器佈局管理器的工作。
  • 應該首先在paintComponent重寫中調用super.paintComponent(g)
  • 我會避免給我的班級一個與公共核心班級衝突的名字。