JToggleButton with ItemListener (Another Example)

setIcon( ) method possible to change the icon inside a JButton during program execution.

Program

cxvdxcvcxv

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

class Frame extends JFrame implements ItemListener{
 
    private JToggleButton jtb;
    private JButton jb;
 
    Frame()
    {
        setTitle("JToggleButton with ItemListener");
        setLayout(new FlowLayout());
        setJToggleButton();
        setAction();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    private void setJToggleButton()
    {
        jtb = new JToggleButton("Start");
        add(jtb);
        jb = new JButton(new ImageIcon("unload.png"));
        add(jb);
    }
 
    private void setAction()
    {
        jtb.addItemListener(this);
    }
 
    public void itemStateChanged(ItemEvent eve)
    {
        if(jtb.isSelected())
        {
            jtb.setText("Stop");
            jb.setIcon(new ImageIcon("loading.gif"));
        }
        else{
            jtb.setText("Start");
            jb.setIcon(new ImageIcon("unload.png"));
        }
    }
}

public class javaapp {
 
    public static void main(String[] args) {
     
        Frame frame = new Frame();
    }
}

Leave a Comment