动态更改jButton图标
我有一个程序可以检测某些机器何时在线并创建一个带有绿色“在线”图标的按钮来显示这一点。 我想添加function以定期检查此机器是否仍在线,如果不是,请将图标更改为我已定义的“离线”图标。
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
可能你在Swing中遇到Concurency问题,这意味着所有Swing代码都必须在EDT上完成
那么你必须将myButton.setIcon(myIcon)
包装到invokeLater()
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { myButton.setIcon(myIcon); } });
我有一个程序可以检测某些机器何时在线并创建一个带有绿色“在线”图标的按钮来显示这一点。
请使用JToggleButton
,如此处所示1和此处 2 。
一旦按钮显示,我无法想出办法。
要切换状态并触发一个动作事件doClick()
或者另外setSelected(boolean)
。
截图
您应该可以使用AbstractButton.setIcon()来完成此操作。 它可能要求您调用按钮上的invalidate()
以显示更改。
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);
btn1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/url.png")));
你可以在按钮上添加一个动作监听器,然后在其被调用的函数中更改图标 – 这是一个例子:
public yourDialogSwing() { Yourbutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onButtonPressed(); } }); } private void onButtonPressed() { YourButton.setIcon(YourButton.getPressedIcon()); }