Java JCheckbox get from selection event

Description

Java JCheckbox get from selection event

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

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

class Demo extends JPanel implements ItemListener {
   JLabel jlab;/* w  ww. j a  v  a  2 s.c  o m*/

   Demo() {

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

      // Add check boxes to the content pane.
      JCheckBox cb = new JCheckBox("C");
      cb.addItemListener(this);
      add(cb);

      cb = new JCheckBox("C++");
      cb.addItemListener(this);
      add(cb);

      cb = new JCheckBox("Java");
      cb.addItemListener(this);
      add(cb);

      cb = new JCheckBox("Perl");
      cb.addItemListener(this);
      add(cb);

      // Create the label and add it to the content pane.
      jlab = new JLabel("Select languages");
      add(jlab);
   }

   // Handle item events for the check boxes.
   public void itemStateChanged(ItemEvent ie) {
      JCheckBox cb = (JCheckBox) ie.getItem();

      if (cb.isSelected())
         jlab.setText(cb.getText() + " is selected");
      else
         jlab.setText(cb.getText() + " is cleared");
   }
}

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