Adv Java - [Swing: JCheckbox Class]

♠ Posted by Unknown in at 20:19

JCheckbox class


The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of AbstractButton.
Some of its constructors are shown here:

     JCheckbox(Icon i)
     JCheckbox(Icon I, boolean state)
     JCheckbox(String s)
     JCheckbox(String s, boolean state)
     JCheckbox(String s, Icon i)
     JCheckbox(String s, Icon I, boolean state)

The state of the check box can be changed via the following method:

     void setSelected(boolean state)

when a check box is selected or deselected, an item event is generated. This is handled by itemStateChanged(). Inside itemStateChanged(), the getItem() method gets the JCheckbox object that generated the event. The getText() method gets the text for that check box and uses it to set the text inside the text field.

Example:

/*
<APPLET CODE = "MCA16.CLASS" WIDTH = 500 HEIGHT = 500></APPLET>
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class  MCA161 extends JApplet implements ItemListener
{
          JTextField jtf;
          public void init()
          {
                   Container contentPane = getContentPane();
                   contentPane.setLayout(new FlowLayout());

                   JCheckBox cb = new JCheckBox("C");
                   cb.addItemListener(this);
                   contentPane.add(cb);
Image: Swing JCheckBox Example
                   cb = new JCheckBox("C++");
                   cb.addItemListener(this);
                   contentPane.add(cb);

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

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

                   jtf = new JTextField(15);
                   contentPane.add(jtf);
          }

          public void itemStateChanged(ItemEvent ie)
          {
                   JCheckBox cb = (JCheckBox) ie.getItem();
                   jtf.setText(cb.getText());
          }

}

0 comments:

Post a Comment