简体   繁体   English

动态更改 jButton 图标

[英]Dynamically change jButton icon

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.我想添加功能来定期检查这台机器是否仍然在线,如果不是,请将图标更改为我已经定义的“离线”图标。

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可能您在 Swing 中遇到了并发问题,这意味着所有 Swing 代码都必须在 EDT 上完成

then you have to wrap myButton.setIcon(myIcon) to the invokeLater() , for example然后你必须将myButton.setIcon(myIcon)包装到invokeLater() ,例如

SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
        myButton.setIcon(myIcon);
    }
});

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 here 1 & here 2 .请改用JToggleButton ,如此1此处2 所示

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) .切换状态并触发动作事件doClick()setSelected(boolean)

Screenshots截图

You should be able to do so using AbstractButton.setIcon() .您应该可以使用AbstractButton.setIcon()来做到这一点。 It may require you to call invalidate() on the button to get the change displayed.它可能需要您在按钮上调用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")));

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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM