I'm trying to create a gui in java swing that lets the user book seats using a toggle button. I have the default button colour initially to test if the click event works. The button should turn red to signify its been booked and turn yellow to signify its been unbooked.
Here is my actionPerformed method
@Override
public void actionPerformed(ActionEvent e) {
GoldSeat seat = (GoldSeat)e.getSource();
if(seat.isSelected()){
seat.setBackground(Color.red);
}
else
{
seat.setBackground(Color.yellow);
}
}
GoldSeat is simply a derived class of JToggleButton. For some reason, when I click the button, it doesn't turn red (it turns to the default grey colour), but when I clicked it again it turns to yellow. So it would seem the 'true' or 'on' state of the button isn't working but the 'false' is. I have no idea why the isSelected() isn't functioning properly.
Any idea how to solve this?
EDIT: I threw together a quick JFrame with one JToggleButton on it using the simple drag and drop interface of Netbeans which generated this code:
jToggleButton1 = new javax.swing.JToggleButton();
jToggleButton1.setText("jToggleButton1");
jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton1ActionPerformed(evt);
}
});
And the action event:
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jToggleButton1.isSelected()){
jToggleButton1.setBackground(Color.red);
}else {
jToggleButton1.setBackground(Color.yellow);
}
}
This performs what I want to happen but I can't recreate it with my derived class that I posted above. Am I doing something wrong with my own code?
The LAF does custom painting when a toggle button is selected, so setting the background has no effect.
You might be able to use the UIManager
to control this behaviour. Before you create any toggle button you can try:
UIManager.put("ToggleButton.select", Color.RED);
This will change the property for all toggle buttons.
Edit:
If you only want this feature for a single toggle button you can try (not sure if it will work) something like:
Color select = UIManager.getColor("ToggleButton.select");
UIManager.put("ToggleButton.select", Color.RED);
JToggleButton button = new JToggleButton(...);
UIManager.put("ToggleButton.select", select);