You can use an else
to take a different action. However, the state of the green color needs to be part of the object fields, not defined in the action method (as it would be reset to false for each action then).
It might also be more clear if you separate the check for the source and the check for color selection.
... object definition ...
boolean isGreen = false;
... action listener...
Object o = evt.getSource();
if (o.equals(lblSI)) {
if (isGreen) {
lblSI.setBackground(Color.RED);
} else {
lblSI.setBackground(Color.GREEN);
}
isGreen = !isGreen;
}
Adding a complete example that instead sets the foreground color as background color will not work on all platforms.
public class RedGreen implements Runnable {
private JButton press;
@Override
public void run() {
JFrame frame = new JFrame("RedGreen");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
press = new JButton("Press");
press.addActionListener(new ActionListener() {
boolean isGreen = false;
@Override
public void actionPerformed(ActionEvent e) {
if (isGreen) {
press.setForeground(Color.RED);
} else {
press.setForeground(Color.GREEN);
}
isGreen = !isGreen;
}
});
frame.getContentPane().add(press);
frame.pack();
frame.setVisible(true);
}
public static void main(String...args) throws Exception {
SwingUtilities.invokeAndWait(new RedGreen());
}
}