繁体   English   中英

正在调用PaintComponent()但未绘制JComponent

[英]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(...) 此方法仅用于绘画和绘画。
  • 你的界限和你的绘画区域是相同的 - 但它们代表两种截然不同的东西。 边界是组件相对于其容器的位置,绘制x,y是相对于JComponent本身的。 所以你画出了你的界限。
  • 所以同样,你的drawButton方法应该绘制为0,0: g.drawRect(0, 0, size.width, size.height);
  • setBounds都不应该调用setBounds 那是布局经理的工作。 通过这样做,您添加了一整层潜力,很难找到错误。
  • 我会覆盖getPreferredSize()来帮助设置组件的最佳大小(编辑 - 你已经做过,虽然以一种非常简单的方式)。
  • 您不应该在按钮内设置按钮的位置 - 再次,这是其容器的布局管理器的工作。
  • 应该首先在paintComponent覆盖中调用super.paintComponent(g)
  • 我会避免给我的班级一个与普通核心班级冲突的名字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM