Java JToggleButton handle selection event

Description

Java JToggleButton handle selection event

// Demonstrate JToggleButton. 
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

class Demo extends JPanel {

   JLabel jlab;//from www.j a  va2 s. com
   JToggleButton jtbn;

   public Demo() {

      // Change to flow layout.
      setLayout(new FlowLayout());

      // Create a label.
      jlab = new JLabel("Button is off.");

      // Make a toggle button.
      jtbn = new JToggleButton("On/Off");

      // Add an item listener for the toggle button.
      jtbn.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent ie) {
            if (jtbn.isSelected())
               jlab.setText("Button is on.");
            else
               jlab.setText("Button is off.");
         }

      });

      // Add the toggle button and label to the content pane.
      add(jtbn);
      add(jlab);
   }
}

public class Main {
   public static void main(String[] args) {
      Demo panel = new Demo();

      JFrame application = new JFrame();

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      application.add(panel);
      application.setSize(250, 250);
      application.setVisible(true);
   }
}



PreviousNext

Related