简体   繁体   English

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

[英]My JButton stays on the screen after being pressed

My JButton's code is here: 我的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);

This should make my screen go black after my button is pressed, but the button just stays on my JFrame. 按下按钮后,这应该会使我的屏幕变黑,但是按钮仅停留在我的JFrame上。 I can't find what is going wrong with this JButton, as I have in the past. 我找不到像过去那样的JButton出了什么问题。
Another error I am encountering is that my JButton takes up the whole screen, even though I set its bounds to be a specific area. 我遇到的另一个错误是,即使我将其边界设置为特定区域,我的JButton也占据了整个屏幕。

You probably degine the Graphics g before the JButton b , thus the JButton is always displayed on the top layer. 您可能在JButton b之前对Graphics g进行脱胶,因此JButton始终显示在顶层。

You have to explicitely hide the button on the click action using the setVisible(false) method. 您必须使用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);
    }
});

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

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