JToggleButton with ItemListener

JToggleButton generates an action event each time it is pressed. However, JToggleButton is generates an item event. This event is used by those components that support the concept of selection. When a JToggleButton is pressed in, it is selected. When it is popped out, it is deselected.

To handle item events, you must implement the ItemListener interface. This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. A toggle button’s state is by calling the isSelected( ) method on the button that generated the event.

setText( ) method possible to change the text inside a JButton during program execution.

Program

tere

 

 

 

Program Source

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

class Frame extends JFrame implements ItemListener{
 
    private JToggleButton jtb;
 
    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("ON");
        add(jtb);
    }
 
    private void setAction()
    {
        jtb.addItemListener(this);
    }
 
    public void itemStateChanged(ItemEvent eve)
    {
        if(jtb.isSelected())
            jtb.setText("OFF");
        else
            jtb.setText("ON");
 
    }
}

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

Leave a Comment