Dynamically change jButton icon

后端 未结 5 1222
Happy的楠姐
Happy的楠姐 2021-01-19 22:14

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 perio

5条回答
  •  隐瞒了意图╮
    2021-01-19 22:24

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

提交回复
热议问题