【发布时间】:2015-04-05 14:46:29
【问题描述】:
基本上,我在绘制自己制作的自定义组件时遇到问题。每当调用 repaint() 时,我的 Button 类的 paintComponent() 就会被调用,但我的框架中没有显示任何内容。我也知道组件的大小和位置正确,因为我设置了边框来检查这一点。
以下是我的自定义组件类:
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);
奇怪的是,当在 main_menu 上调用 repaint() 时,即使调用了 Button 的 paintComponent(),也会绘制 JComboBox 而不是 Button。
【问题讨论】: