Credits

Sunday, February 20, 2011

Java's Check Box

A check box is somehow similar to a button, however, it does not bounce back when click on instead, it can be toggled to on and off mode.


An event can be initiated on check box using the ItemEvent and using the constant ItemEvent.SELECTED and DESELECTED, a user can determine which item is chosen.


A constructor for JCheckBox states as follows:


JCheckBox bold = new JCheckBox("Bold", true);  //default selection
JCheckBox italic = new JCheckBox("Italic");


See the program below for application of JCheckBox.
[+/-] show/hide


/* sample use of JCheckbox with Item event */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JCheckBoxEvent extends JFrame implements ItemListener{

Container con = getContentPane();
JCheckBox bold = new JCheckBox("Bold");
JCheckBox italic = new JCheckBox("Italic");
JTextField result = new JTextField("",25);


//constructor for JCheckBoxEvent

public JCheckBoxEvent()
{ super("JCheckBox Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con.setLayout(new GridLayout(0,1));
con.add(bold);
con.add(italic);
con.add(result);

//adding an item listener
bold.addItemListener(this);
italic.addItemListener(this);
result.setEditable(false);

setContentPane(con);


}

public void itemStateChanged(ItemEvent e){
Font ShowFont;
String text;
int style;

text = "12 point";
style =0;

Object source = e.getSource();

if (source==bold){
int select = e.getStateChange();
if(select == ItemEvent.SELECTED){
style=style|Font.BOLD;
text +=" boldface";
}
else text +=" regular weight";
}
else if (source==italic){
int select = e.getStateChange();
if(select == ItemEvent.SELECTED){
style=style|Font.ITALIC;
text +=" italic";
}
else text +=" roman";
}

text += " font";
ShowFont = new Font("Arial",style,12);
result.setFont(ShowFont);
result.setText(text);

}


public static void main (String[] args)
{ JFrame aFrame = new JCheckBoxEvent();
aFrame.setSize(250,150);
aFrame.setVisible(true);
}}

AddThis