My GUI has a list of filtered entries from a db file. For each entry, I have a select Jbutton which shows more details for each entry.
What I am trying to achieve is to have the select JButton change color when pressed, and revert to original color when another entry's button is selected.
The code I have at the moment will change the selected color's button just fine, but remains the same color when another entry's Details button is selected:
//within for loop for each object in database
JButton selectedButton = new JButton("Details");
selectButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
entry.vehicleSelected();
if(e.getSource() instanceof JButton )
((JButton)e.getSource()).setBackground(Color.RED);
((JButton)e.getSource()).setOpaque(true);
((JButton)e.getSource()).setContentAreaFilled(false);
}});
How can I change the code so I can get this effect?
You can introduce a field JButton buttonToReset
where the last pressed button is saved and use it
public void actionPerformed(ActionEvent e) {
entry.vehicleSelected();
if(e.getSource() instanceof JButton )
((JButton)e.getSource()).setBackground(Color.RED);
((JButton)e.getSource()).setOpaque(true);
((JButton)e.getSource()).setContentAreaFilled(false);
if (buttonToReset!=null) {
buttonToReset.setBackground(UIManager.getColor("Button.background"));
}
buttonToReset = ((JButton)e.getSource());
}});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.