My JButton's code is here:
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. I can't find what is going wrong with this JButton, as I have in the past.
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.
You probably degine the Graphics g
before the JButton b
, thus the JButton is always displayed on the top layer.
You have to explicitely hide the button on the click action using the setVisible(false) method.
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
b.setVisible(false);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 1000, 500);
}
});