Showing posts with label itemlistener. Show all posts
Showing posts with label itemlistener. Show all posts

Saturday, August 24, 2013

JCheckBox

JCheckBox represents a check box item that can be turned on or turned off. You can turn on or turn off a number of items. The JCheckBox component can generate item event so you need to use the ItemListener interface to receive the event. Alternatively, you also can use the AbstractAction class that implements the Action Interface to handle the action event that is generated by the JCheckBox as you can do with JButton.

Constructors of the JCheckBox class:
-JCheckBox()
creates a new checkbox.
-JCheckBox(String text)
creates a new checkbox with specified text.
-JCheckBox(String text, boolean state)
creates a new checkbox with specified text and selection state.
-JCheckBox(Action action)
creates a new checkbox with properties taken from the implementation of the Action interface.
-JCheckBox(Icon icon)
creates a new CheckBox with an image icon.
-JCheckBox(Icon icon, boolean state)
creates a new CheckBox with an image icon and specified selection state.
-JCheckBox(String text,Icon icon)
creates a new checkbox with specified text and image icon.

Useful methods of the JCheckBox class:
-getText():String
returns the text of the checkbox.
-isSelected():boolean
determines whether or not the checkbox is selected.
-setText(String text)
sets the text of the checkbox.

Example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicBorders;

class JCheckBoxShow extends JFrame implements ItemListener{
JLabel lbl;
JCheckBoxShow(String title){
setTitle(title);
setSize(400,300);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
String[] hobbies={"Flower arranging","Mountain biking","Card playing","Football watching","Game playing"};
JPanel p=new JPanel();
p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
p.setBorder(new BasicBorders.ButtonBorder(Color.RED,Color.BLACK,Color.GREEN,Color.YELLOW));
contpane.add(new JLabel("What do you do in your free time?"), BorderLayout.NORTH);
for(String h:hobbies){
p.add(new JCheckBox(h));

}
for(int i=0;i<p.getComponentCount();i++)
{
JCheckBox ch=(JCheckBox)p.getComponent(i);
ch.addItemListener(this);
}
contpane.add(p,BorderLayout.CENTER);
lbl=new JLabel();
contpane.add(lbl,BorderLayout.SOUTH);
setVisible(true);

}

public void itemStateChanged(ItemEvent e){
JCheckBox ch=(JCheckBox)e.getSource();
if(ch.isSelected())
lbl.setText(lbl.getText()+" "+ch.getText());
else
lbl.setText(lbl.getText().replaceAll(ch.getText(),""));
}

}

public class JFrameSwing {
public static void main(String[] args){
new JCheckBoxShow("JCheckBox");
}
}

JCheckBox Swing

To get the number of components added to the container, you can use its getComponentCount() method. If you want to visit every component of the container, you will need to use a loop. Each component in the container can be retrieved by using its getComponent(int index) method.

Monday, August 5, 2013

ItemListener

ItemListener is an interface to receive item event that is generated by Checkbox, Choice, and List components when an item of the Checkbox object is turned on or turned of or when an item of the Choice or List object is selected.

A class that wants to receive the item event must implement the ItemListener interface. Then listener is registered with the source component by using the addItemListener(ItemListener listener) method. The ItemListener has the itemStateChanged(ItemEvent e) method that need to be overridden to cause an action to happen.

Example:

import java.awt.Choice;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame implements ItemListener{
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout());
changeSize("200x150");
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Choice listsizes=new Choice();
listsizes.addItemListener(this);
listsizes.add("200x150");
listsizes.add("300x250");
listsizes.add("400x350");
listsizes.add("500x350");
listsizes.add("600x450");
listsizes.add("700x450");
listsizes.add("800x550");
add(new Label("Select window size:"));
add(listsizes);
validate();
}

public void changeSize(String d){
String[] di=d.split("x");  
  setSize(Integer.parseInt(di[0]),Integer.parseInt(di[1]));
}
public void itemStateChanged(ItemEvent e){

changeSize(e.getItem().toString());
}

}
public class ItemListenerTest {
public static void main(String[] args){
new InterfaceShow("ItemListener");

}
}
ItemListener ItemEvent

In the example code above,  the Choice component, listsizes is used to store strings. Each string represents a dimension (width and height) of the window. When the user selects a dimension from the Choice component, an action happens. The action to perform is resetting the size or dimension of the window. The code of the action is written in the itemStateChanged method. Since each dimension is a string that contains width and height, we need to separate it in to integer values that represent a width and height. Then the setSize method is used to resize the size of the window.

Friday, July 26, 2013

List

List is a component that allows you to create a scrolling list of text items. You can configure the list for single or multiple selection. The List can generate item event. To receive the event, the application must implement the ItemListener and register the listener.

Constructors of the List class:
-List()
creates a new scrolling list.
-List(int rows)
creates a new scrolling list with the number of visible rows.
-List(int rows, boolean multipleMode)
creates a new scrolling list with the number of visible rows and selection mode.

Useful methods of the List class:
-add(String text)
adds text item to the end of the list.
-add(String text,int index)
adds text item to the list at the specified position.
-deselect(int index)
delects the text item at the specified index.
-getItem(int index)
gets text item at the specified index.
-getItemCount()
get the number of text items in the list.
-getItems()
gets all text items in the list.
-getSelectedItem()
gets the selected text item.
-getSelectedItems()
get all selected text items.
-isIndexSelected(int index)
determines whether or not the text item at the specified index is selected. 
-remove(int index)
removes the text item at the specified index.
-remove(String item)
removes the text item that matches the item argument.
-removeAll()
removes all text items of the list.
-select(int index)
select the text item at the specified index.
-setMultipleMode(boolean multipleMode)
sets selection mode of the list to false or true. If false, only a single text item can be selected. 

In the example program below, we construct a List component to display 15 rows of items with single item selection. If the number of items added to the List beyond this rows limit, the scroll bars are automatically attached to the list for you.  The getAllFonts method of the GraphicsEnvironment class is used to retrieve all font objects from the system. All font objects are added to the List component by using its add method.

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Label;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


class InterfaceShow extends Frame implements ItemListener{
Label lbl;
InterfaceShow(String title){
setTitle(title);
setSize(new Dimension(500,300));
setLayout(new FlowLayout(FlowLayout.LEFT));
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
List lst=new List(15,false);
lst.addItemListener(this);
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fs=ge.getAllFonts();
for(Font f:fs){
lst.add(f.getName());
}
lbl=new Label();
add(lst);
add(lbl);
validate();
}
public void itemStateChanged(ItemEvent e){
List l=(List)e.getSource();
String text=l.getSelectedItem();
lbl.setText(text);
validate();
}

}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using List");
}
}

List awt

Thursday, July 25, 2013

Choice

Choice displays a list of items in a box in which only one item can be selected by the user. The Choice can generate item event so the application that wants to perform action when the item of the Choice is selected must implement the ItemListener interface and uses the addItemListener(ItemListener listener) method to register the listener to receive the event.

Constructor of the Choice class:
-Choice()
Useful methods of the Choice class:
-add(String text)
adds text item to the Choice box.
-getItem(int index)
reads the text item at the specified index.
-getItemCount()
counts all text items in the Choice box.
-getSelectedItem()
reads the selected item.
-insert(String text,int index)
inserts text item at the specified index.
-remove(int index)
removes the text item at the specified index.
-remove(String item)
removes the text item that matches the item argument.
-removeAll()
removes all items in the Choice box.
-select(int index)
selects the tex item at the specified index.
-select(String text)
slects the tex item that matches the item argument.

In the example code below, the Choice object, clist is created without an item. Later, its add method is used to add a list of numbers with 0 lower bound and 4999 upper bound. One of these numbers will be selected from the Choice, clist and is used as color code when constructing the color object to be used as the background color of the window.

import java.awt.Choice;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout());
setSize(new Dimension(500,300));

setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Label lbl=new Label("Select background color:");
Choice clist=new Choice();
for(int rgb=0;rgb<5000;rgb+=100)
clist.add(rgb+"");
clist.addItemListener(new ItemList());
add(lbl);
add(clist);
setBGColor(0);
validate();
}
public void setBGColor(int rgb){
setBackground(new Color(rgb));
}
class ItemList implements ItemListener{
public void itemStateChanged(ItemEvent e){
setBGColor(Integer.parseInt(e.getItem().toString()));
}
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using Choice");

}
}

Choice in awt

Wednesday, July 24, 2013

Checkbox vs. CheckboxGroup

With Checkbox class you are able to create a list of items that their states can be turned on or off. You can turn on or turn off multiple items. However, if you want to allow a single item to be turned on or off, you must place the checkboxes in CheckboxGroup.

The Checkbox can generate item event. To receive the item event, the application must implement ItemListener interface and uses the addItemListener(ItemListener listener) method. The ItemListener interface has itemStateChanged(ItemEvent e) that needs to be overridden to perform action when the user selects or deselect the items.

Constructors of Checkbox class:
-Checkbox()
creates a check box without label.
-Checbox(String label)
creates a check box with label.
-Checkbox(String label, boolean state)
creates a check box with label and allowing state input to turn on or turn off the check box.
-Checkbox(String label, boolean state, CheckboxGroupd group)
creates a check box with label and allowing state input to turn on or turn off the check box and specifying check box group.

Useful methods of the Checkbox class:

-getLabel():String
reads the label from the check box.
-getState():boolean
reads the state of the check box.
-setLabel(String label):void
sets the label to the check box.
-setState(boolean state):void
sets the state to the check box.



Example:

import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
private Label lbl;
private Checkbox course1;
private Checkbox course2;
private Checkbox course3;
private Checkbox course4;

InterfaceShow(String title){
setTitle(title);
setLayout(new BorderLayout());
setSize(new Dimension(500,300));

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

course1=new Checkbox("C++",true);
course1.addItemListener(new ItemList());
course2=new Checkbox("VB.NET",false);
course2.addItemListener(new ItemList());
course3=new Checkbox("Java",true);
course3.addItemListener(new ItemList());
course4=new Checkbox("Software Engineering",false);
course4.addItemListener(new ItemList());
Panel p=new Panel();
p.setLayout(new GridLayout(5,1));
p.add(new Label("Select your favorite courses:"));
p.add(course1);
p.add(course2);
p.add(course3);
p.add(course4);
add(p, BorderLayout.NORTH);
lbl=new Label();
lbl.setForeground(Color.BLUE);
add(lbl,BorderLayout.CENTER);
setVisible(true);
validate();
}

class ItemList implements ItemListener{
public void itemStateChanged(ItemEvent e){
if(e.getSource()==course1){
lbl.setText("You have selected "+course1.getLabel());

}
else if(e.getSource()==course2){
lbl.setText("You have selected "+course2.getLabel());

}
else if(e.getSource()==course3){
lbl.setText("You have selected "+course3.getLabel());

}
else {
lbl.setText("You have selected "+course4.getLabel());
}

}
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using Checkbox and CheckboxGroup");

}
}


checkbox multiple selections


If you want to allow only a single item selection, replace part of the code:
course1=new Checkbox("C++",true);
course1.addItemListener(new ItemList());
course2=new Checkbox("VB.NET",false);
course2.addItemListener(new ItemList());
course3=new Checkbox("Java",true);
course3.addItemListener(new ItemList());
course4=new Checkbox("Software Engineering",false);
course4.addItemListener(new ItemList());

with the code:
CheckboxGroup cg=new CheckboxGroup();
course1=new Checkbox("C++",false,cg);
course1.addItemListener(new ItemList());
course2=new Checkbox("VB.NET",false,cg);
course2.addItemListener(new ItemList());
course3=new Checkbox("Java",true,cg);
course3.addItemListener(new ItemList());
course4=new Checkbox("Software Engineering",false,cg);
course4.addItemListener(new ItemList());

checkbox single selection