按下后我的 JButton 停留在屏幕上

My JButton stays on the screen after being pressed

我的 JButton 代码在这里:

JButton b = new JButton("JButton");
b.setBounds(100, 100, 100, 50);
b.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 1000, 500);
    }
});
frame.add(b);

这应该会使我的屏幕在按下按钮后变黑,但按钮只停留在我的 JFrame 上。我找不到这个 JButton 有什么问题,就像我过去一样。
我遇到的另一个错误是我的 JButton 占据了整个屏幕,即使我将其边界设置为特定区域。

您可能在JButton b之前定义了Graphics g,因此JButton总是显示在顶层。

您必须使用 setVisible(false) 方法在单击操作中明确隐藏按钮。

b.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        b.setVisible(false);
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 1000, 500);
    }
});