java重绘阻止了jbutton

Ewe*_*wen 0 java graphics swing jcomponent jbutton

在我的paintComponent()方法中,我有一个绘制jpanel背景的drawRect().但由于在调用paintComponent()方法之前在屏幕上绘制了jbutton,因此drawRect会阻止jbutton.有谁知道如何解决这一问题?我的猜测是在重新调用之前添加jbutton,但我不知道该怎么做?

一些代码:

public Frame(){
  add(new JButton());
}

public void paintComponent(Graphics g){
  super.paintComponent(g);
  g.drawRect(0,0,screenwidth,screenheight); //paints the background with a color 
                                            //but blocks out the jbutton.
}
Run Code Online (Sandbox Code Playgroud)

old*_*inb 6

现在,首先,我会告诉你你在这里做错了什么 - JFrame不是一个JComponent,并且没有paintComponent你可以覆盖.您的代码可能永远不会被调用.除此之外,drawRect仅仅绘制一个矩形-它并没有填一个.


但是,我相信有一个正确的方法来做到这一点.

由于您使用的是JFrame,你应该利用容器的的分层窗格通过JFrame.getLayeredPane.

分层窗格是具有深度的容器,使得重叠的组件可以一个在另一个上面.有关分层窗格的常规信息,请参见如何使用分层窗格.本节讨论根窗格如何使用分层窗格的详细信息.

根窗格包含在如何使用根窗格中,这是Java教程的一部分.分层窗格是根窗格的子窗口,而JFrame作为顶级容器的分层窗格使用基础窗格JRootPane.

无论如何,由于您对创建背景感兴趣,请参阅下图,了解分层窗格通常如何在顶级容器中查看:

下表描述了每个图层的预期用途,并列出了与每个图层对应的JLayeredPane常量:

图层名称 - - 描述

FRAME_CONTENT_LAYER - new Integer(-30000)- 根窗格将菜单栏和内容窗格添加到此深度的分层窗格.

由于我们要指定我们的背景是在内容的后面,我们首先将它添加到同一层(JLayeredPane.FRAME_CONTENT_LAYER),如下所示:

final JComponent background = new JComponent() {

  private final Dimension size = new Dimension(screenwidth, screenheight);

  private Dimension determineSize() {
    Insets insets = super.getInsets();
    return size = new Dimension(screenwidth + insets.left + insets.right,
        screenheight + insets.bottom + insets.top);
  }

  public Dimension getPreferredSize() {
    return size == null ? determineSize() : size;
  }

  public Dimension getMinimumSize() {
    return size == null ? determineSize() : size;
  }

  protected void paintComponent(final Graphics g) {
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, screenwidth, screenheight);
  }
};
final JLayeredPane layeredPane = frame.getLayeredPane();
layeredPane.add(background, JLayeredPane.FRAME_CONTENT_LAYER);
Run Code Online (Sandbox Code Playgroud)

现在,为了确保我们在内容之前绘制背景,我们使用JLayeredPane.moveToBack:

layeredPane.moveToBack(background);
Run Code Online (Sandbox Code Playgroud)


Mad*_*mer 5

我做了这个非常快速的测试.正如HovercraftFullOfEels所指出的那样.JFrame没有paintComponent,所以我用了一个JPanel.

你可以看到我吗

这是由此代码生成的

public class PanelTest extends JPanel {

    private JButton button;

    public PanelTest() {

        setLayout(new GridBagLayout());

        button = new JButton("Can you see me ?");
        add(button);

    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        Rectangle bounds = button.getBounds();
        bounds.x -= 10;
        bounds.y -= 10;
        bounds.width += 20;
        bounds.height += 20;

        g.setColor(Color.RED);
        ((Graphics2D)g).fill(bounds);

    }

}
Run Code Online (Sandbox Code Playgroud)

我有我尝试使用复制的问题paintComponentsJFrame,我没有看到矩形.即使我覆盖paintJFrame,矩形仍然在按钮下面绘制(不是我会建议做的).

问题是,你没有给我们足够的代码来知道出了什么问题

ps - drawRect不会"填补"任何东西

  • 我猜测有一些糟糕的嗅觉代码,也许他正在尝试从paintComponent中添加组件 - 很难猜测. (2认同)