I have a program that detects when certain machines are online and creates a button with a green "online" icon to show this. I want to add the functionality to check periodically if this machine is still online, and if it's not, change the icon to the "offline" icon that I've already defined.
5 Answers
I know how to set the icon, however I can't figure out a way to do it once the button has already been displayed
probably you have issues with Concurency in Swing, that means that all Swing code must be done on EDT
then you have to wrap myButton.setIcon(myIcon)
to the invokeLater()
, for example
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myButton.setIcon(myIcon);
}
});

- 168,117
- 40
- 217
- 433

- 109,525
- 20
- 134
- 319
I have a program that detects when certain machines are online and creates a button with a green "online" icon to show this.
Use a JToggleButton
instead, as shown here1 & here2.
I can't figure out a way to do it once the button has already been displayed.
To toggle the state and fire an action event doClick()
or alternately setSelected(boolean)
.
Screenshots

- 1
- 1

- 168,117
- 40
- 217
- 433
You should be able to do so using AbstractButton.setIcon().
It may require you to call invalidate()
on the button to get the change displayed.
changeButton = new JButton(icon1);
changeButton.addActionListener(
new ActionListener( )
{
private boolean flag = true;
@Override
public void actionPerformed( ActionEvent arg0 )
{
changeButton.setIcon( flag ? icon2 : icon1 );
flag = !flag;
}
}
);
add(changeButton);

- 8,198
- 71
- 51
- 66
-
I know how to set the icon, however I can't figure out a way to do it once the button has already been displayed. – Fallso Nov 01 '11 at 12:25
-
You can use this when the JButton is already drawn. I have added a code snippet to demonstrate this: a JButton that changes it's icon when it is clicked. – S.L. Barth is on codidact.com Nov 01 '11 at 13:01
btn1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/url.png")));

- 570
- 1
- 5
- 20
you can add an action listener on the button, then in its called function change the icon - here is an example :
public yourDialogSwing() {
Yourbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onButtonPressed();
}
});
}
private void onButtonPressed() {
YourButton.setIcon(YourButton.getPressedIcon());
}

- 3,676
- 2
- 30
- 34