[英]PaintComponent() being called but JComponent not being painted
基本上我在绘制我制作的自定义组件时遇到了问题。 每当调用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。
几个问题:
paintComponent
方法(如paintComponent
setBounds(...)
调用setBounds(...)
。 此方法仅用于绘画和绘画。 drawButton
方法应该绘制为0,0: g.drawRect(0, 0, size.width, size.height);
setBounds
都不应该调用setBounds
。 那是布局经理的工作。 通过这样做,您添加了一整层潜力,很难找到错误。 getPreferredSize()
来帮助设置组件的最佳大小(编辑 - 你已经做过,虽然以一种非常简单的方式)。 super.paintComponent(g)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.