Reputation: 133
I want the background color of a JButton
to change when I click on it with the mouse. The first time I click on it, I want the background to be red. The second time I click on it, I want the color to be blue.
So far I have not succeeded. Here is my code.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == "red")
{
jButton1.setBackground(Color.red);
}
else
{
jButton1.setBackground(Color.blue);
}
}
Here is a scrren capture of my app.
Upvotes: 0
Views: 121
Reputation: 6808
The Look & Feel you are using handles the background of the buttons, hence you cannot change it. You might be able to change it (but it will look ugly - my opinion) by doing:
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setOpaque(true);
button.setBackground(Color.BLUE);
In order to test it and make sure its that, run the following SSCCEs:
Without LAF where background can be changed:
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JButton button = new JButton("1");
button.setBackground(Color.BLUE);
button.addActionListener(e -> {
Color newBackground = button.getBackground().equals(Color.RED) ? Color.BLUE : Color.RED;
button.setBackground(newBackground);
});
frame.add(button);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
});
}
And with windows look and feel where it cannot be changed, because "windows paint the button".
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
//Install windows LaF
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JButton button = new JButton("1");
button.setBackground(Color.BLUE);
button.addActionListener(e -> {
Color newBackground = button.getBackground().equals(Color.RED) ? Color.BLUE : Color.RED;
button.setBackground(newBackground);
});
frame.add(button);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
});
}
You will see that in the second example, background will not change (entirely). There is no way to change the background and keep the look and feel. You will have to do all the painting your self, and I do not think it will be easy.
Also, the if statement:
evt.getSource() == "red"
Will never be true. You might want to think better the condition. To compare strings you will have to use String#equals
method. To compare it with a component (variable named red
) (because evt.getSource() will likely return a component object) you will have to if (evt.getSource() == red) ...
Upvotes: 1