How can we implement a JToggleButton in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

JToggleButton

  • A JToggleButton is an extension of AbstractButton and it can be used to represent buttons that can be toggled ON and OFF.
  • When JToggleButton is pressed for the first time, it remains pressed and it can be released only when it is pressed for the second time.
  • A JToggleButton generates an ActionEvent each time it is pressed.
  • A JToggleButton can also generate an ItemEvent, 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.

Example

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JToggleButtonTest extends JFrame implements ItemListener {
   private JToggleButton jtb;
   JToggleButtonTest() {
      setTitle("JToggleButton Test");
      setLayout(new FlowLayout());
      setJToggleButton();
      setAction();
      setSize(450, 300);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   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 MainApp {
   public static void main(String[] args) {
      new JToggleButtonTest();
   }
}

Output


raja
Published on 08-Jul-2019 18:20:11
Advertisements