动态更改jButton图标

时间:2011-11-01 12:17:48

标签: java swing jbutton

我有一个程序可以检测某些机器何时在线,并创建一个带有绿色“在线”图标的按钮来显示此信息。我想添加功能以定期检查此机器是否仍在线,如果不是,请将图标更改为我已定义的“离线”图标。

5 个答案:

答案 0 :(得分:8)

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

可能您遇到Concurency in Swing问题,这意味着所有Swing代码都必须在EDT上完成

然后你必须将myButton.setIcon(myIcon)包裹到invokeLater(),例如

SwingUtilities.invokeLater(new Runnable() {

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

答案 1 :(得分:4)

  

我有一个程序可以检测某些机器何时在线,并创建一个带有绿色“在线”图标的按钮来显示此信息。

改为使用JToggleButton,如图所示here 1 & here 2

  

一旦按钮显示,我无法想办法。

切换状态并触发操作事件doClick()或者setSelected(boolean)

截图

答案 2 :(得分:1)

您应该可以使用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);

答案 3 :(得分:1)

btn1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/url.png")));

答案 4 :(得分:0)

你可以在按钮上添加动作监听器,然后在其被调用的函数中更改图标 - 这是一个例子:

public yourDialogSwing() {

        Yourbutton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onButtonPressed();
            }
        });
}

private void onButtonPressed() {
       YourButton.setIcon(YourButton.getPressedIcon());
}