如何使 fillPolygon(s) 支持 JButtom

How to make fillPolygon(s) behined JButtom

[奇怪的渲染] 首先对不起我的英语。 我遇到了一个奇怪的渲染错误:fillPolygon 在 2. 和 3. JButton 前面渲染,如果我将鼠标移到按钮上,渲染会突然变得正确。我不确定是什么问题。 我制作了一个充满星星的 BufferedImage(我也尝试过不使用 BufferedImage)。

public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(background, 0 , 0, null );
}

按钮设置:

    for(int i = 0; i < buttons.length; i++) {
        buttons[i] = new JButton(names[i]);
        buttons[i].setFont(font);
        buttons[i].addActionListener(al);
        buttons[i].setActionCommand(actionCommands[i]);
        buttons[i].setVisible(defaultButtonVisibility[i]);
    }

面板设置:

private void panelSetup(Color background) {
    panel = new JPanel();
    panel.setSize(getSize());
    panel.setBackground(background);
    panel.setLayout(new GridBagLayout());
    
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    
    for(int i = 0; i < 5; i++) panel.add(buttons[i], gbc);
    makeBackground();
}
public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(background, 0 , 0, null );
}

当您进行自定义绘画时,您应该覆盖 paintComponent() 方法:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(background, 0 , 0, null );
}

阅读 A Closer Look at the Paint Mechanism 上的 Swing 教程部分。

您会看到组件及其所有子项都已绘制,然后您尝试在它们之上绘制图像。对于背景,您需要先绘制面板的背景,然后再绘制子组件。

if I move the mouse over the buttons the rendering suddenly turns to correct.

这是因为需要重新绘制按钮以反映“滚动”效果。所以按钮暂时被绘制在背景之上。

但是,尝试调整框架大小,背景会再次出现,因为整个框架都被重新绘制了。