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。