【问题标题】:PaintComponent() being called but JComponent not being painted调用 PaintComponent() 但未绘制 JComponent
【发布时间】: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。

【问题讨论】:

    标签: java swing


    【解决方案1】:

    几个问题:

    • 你不应该在诸如paintComponent之类的绘画方法中调用setBounds(...)。此方法仅用于绘画和绘画。
    • 你的边界和你的绘画区域是一样的——但是它们代表了两个非常不同的东西。边界是组件相对于其容器的位置,绘画 x、y 是相对于 JComponent 本身。所以你的绘画超出了你的界限。
    • 同样,您的 drawButton 方法应该在 0、0 处绘制:g.drawRect(0, 0, size.width, size.height);
    • setBounds 无论如何都不应该被调用。那是布局经理的工作。通过这样做,您会增加一整层潜在且难以发现的错误。
    • 我会覆盖 getPreferredSize() 以帮助设置组件的最佳大小(编辑 -- 您已经这样做了,尽管是以非常简单的方式)。
    • 您不应该在按钮内设置按钮的位置 -- 再说一遍,这是其容器的布局管理器的工作。
    • super.paintComponent(g) 可能应该首先在paintComponent 覆盖中调用。
    • 我会避免给我的班级起一个与通用核心班级冲突的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多