Showing posts with label awt. Show all posts
Showing posts with label awt. Show all posts

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

Tuesday, July 23, 2013

TextArea

TextArea class allows you to create a text area in which you can input and edit multiple lines of text. TextArea is able to generate text and key events as the TextField does. Its constructors and useful methods are summarized below.

Constructors of TextArea class:
-TextArea()
creates an empty text area.
-TextArea(int rows, int columns)
creates an empty text area with specifying numbers of rows and columns.
-TextArea(String text, int rows, int columns)
create a text area with default text and specifying numbers of rows and columns.

Useful methods of TextArea class:

-append(String text):void
appends text to the text area.
-getText()
reads text from the text area.
-getSelectedText()
reads selected text from the text area.
-insert(String text, int pos)
inserts text to the text area at the specified position.
-replaceRange(String text, int start,int end)
replaces a rangle of text from start to end positions with the new text specified by text argument.
-select(int start,int end)
selects text in the text area from start to end positions.
-setText(String text)
places text to the text area. The old text will be replaced.

In the example code below, we create a TextArea with 10 rows and 50 columns. To make it bigger you need to increases its row and column values. The scroll bars are automatically attached to text area when the input text reaches the rows or columns limit.

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
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));

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

TextArea txtarea=new TextArea(10,50);
add(txtarea);

setVisible(true);
validate();
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using TextArea");

}
}


textarea awt

Sunday, July 21, 2013

TextField

TextField class allows you to create a text field to input and edit a single line of text. The TextField can generate text event and key event.

To receive text event, the application must implements TextListener interface. You will need to override the textValueChanged (TextEvent e) method of the TextListener interface to perform an action when there is any change to text in the text field. You need to use the addTextListener(TextListener listener) method to register the listener to receive the text event.

To receive key event, the application must implements KeyListener interface and register the listener.You need to use the addKeyListener (KeyListener e) method. The KeyListener interface has three methods: keyPressed(KeyEvent e), keyReleased(KeyEvent e), and keyTyped(KeyEvent e) that can be used to perform action when a key is pressed, released or typed.

Constructors of the TextField class:
-TextField()
creates an empty text field.
-TextField(int columns)
creates an empty text field with specifying the number of columns.
-TextField(String text)
creates a text field with the default text in in.
-TextField(String, int columns)
creates a text box with default text and number of columns.

Useful methods of the TextField class:
-addTextListener(TextListener listener): void
registers the text listener to receive text event from this text field.
-getText(): String
returns the text in the text field.
-setEchoChar(char c):void
sets the echo character for this text field.
-setEditable(boolean editable): void
determines whether or not the text field is editable.


Example: text field with text event

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
private Label lbl;
private TextField txtname;
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout(FlowLayout.CENTER));
//setExtendedState(Frame.MAXIMIZED_BOTH);
setSize(new Dimension(300,200));
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
txtname=new TextField(30);
txtname.addTextListener(new TextList());
lbl=new Label();
lbl.setFont(new Font("Arial",Font.BOLD,30));
add(txtname);
add(lbl);

setVisible(true);
validate();
}

class TextList implements TextListener{
public void textValueChanged(TextEvent e){
lbl.setText(txtname.getText());
validate();
}
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using TextField");

}
}


textfield with text event textlistener


For another example, the text field object is used with the KeyListener interface. To allow only number digits, you need to track the code of character input in the keyTyped method. The digit characters are from 0 to 9 and their equivalent codes are from 48 to 57. The consume method of the KeyEvent class is used to hide an undesirable character.

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
private Label lbl;
private TextField txtname;
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout(FlowLayout.CENTER));
//setExtendedState(Frame.MAXIMIZED_BOTH);
setSize(new Dimension(300,200));
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
txtname=new TextField(30);
txtname.addKeyListener(new KeyList());
lbl=new Label("Enter a number:");
add(lbl);
add(txtname);
setVisible(true);
validate();
}

class KeyList implements KeyListener{
public void keyTyped(KeyEvent e){
int intkey=e.getKeyChar();
if(!(intkey>=48 && intkey<=57))
e.consume();
}
public void keyPressed(KeyEvent e){

}
public void keyReleased(KeyEvent e){

}

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

}
}


text field with key event keylistener

Saturday, July 20, 2013

Button

Button is a component class in AWT package. When a button is pushed, an action can happen. An application that wants to perform some action when the button is pushed has to implement ActionLister interface and registers the new listener to receive events from the button by calling the addActionListener(ActionListener listener) method. The code to perform actions when the button is pushed will be placed in the actionPerformed(ActionEvent e) method of the ActionLister interface.

Constructors of Button class:
-Button()
creates a button with empty label.
-Button(String label)
creates a button with string label.
Useful methods of Button class:
-addActionListener(ActionListener listener): void
registers the new listener to receive events from the button.
-getLabel(): String
reads the label on the button.
-setLabel(String label): void
  set the label to the button.

Example:

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
class ShowImage extends Label{
BufferedImage bi=null;
public void paint(Graphics g){
if(bi!=null)
g.drawImage(bi,0,0,null);
}

public void loadImage(String filename){
try{
bi=ImageIO.read(new File(filename));
}catch(IOException ie){System.out.println("Can't read the image file");}
}
}

class InterfaceShow extends Frame implements ActionListener{
InterfaceShow(String title){
setTitle(title);
setSize(new Dimension(350,300));
setLayout(new BorderLayout());
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Button btshow=new Button("Show image");
btshow.addActionListener(this);
Panel panel=new Panel();
panel.add(btshow);
add(panel, BorderLayout.NORTH);
setVisible(true);

}

public void actionPerformed(ActionEvent e){
ShowImage si=new ShowImage();
si.loadImage("d:/earth.png");
add(si,BorderLayout.CENTER);
validate();

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

}
}
button java

Label

Label is a component in AWT package. It is used to display non-editable text on the window. You can create a label by using the Label class. The Label class is summarized below.

Label constructors:
-Label()
creates a label object without any text on it.
-Label(String text)
creates a label object with text on it.
-Label(String text,int alignment)
creates a label object with text on it and the text alignment is specified.

Useful fields of the Label class:
-CENTER
-LEFT
-RIGHT
Useful methods of the Label class:
-getText()
reads text from the label object.
-setAlignment(int alignment)
sets the text alignment of the label object.
-setText(String text)
sets the text of the label object.
-setForeground(Color color)
sets the text color the label object.
-setFont(Font font)
sets the font of text of the label object.

Example:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

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

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

Label lbl=new Label();
Lbl.setText("This is the text placed on the Label.");
lbl.setFont(new Font("Arial",Font.BOLD,20));
lbl.setAlignment(Label.CENTER);
add(lbl);
setVisible(true);
validate();
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using Label");

}
}

Label in awt

In the example code about, a label object called lbl is created without specifying its text and with the default alignment. The the setText method is used to set the text of the label. Its setFont method is used to set a font object to text of the label. The syntax to create a font object is Font f=new Font(Font_name, Font_style, Font_size). To specify that the text of the label must be left aligned, you need to use the setAlignment method. This method accepts a constant value Label.LEFT, Label.RIGHT, or Label.CENTER. If you supply Label.LEFT to this method, the text of the label will be left aligned. By supplying Label.RIGHT, the text is right aligned and so son.

Friday, July 19, 2013

Frame

In Java, Frame is a class (in awt package) that can be used to create a top-level window in a graphical user interface program. The window that is the instance of the Frame class can have title, border, and menu bar. This contrasts to a window created by the Applet class.

Frame constructors:
-Frame()
-Frame(String title)

Its useful methods:
-add(Component c)
-setExtendedState(int state)
-setLocation(int x,int y)
-setResizable(boolean resizable)
-setSize(int width,int height)
-setSize(Dimension ds)
-setTitle(String title)
-setVisible(boolean visible)

Example:

import java.awt.Frame;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class WindowShow extends Frame{
WindowShow(){
//setExtendedState(Frame.MAXIMIZED_BOTH);
setSize(400,300); //set window size
setTitle("Form"); //set window title
setVisible(true); //make sure the window is visible
Image iconimage=Toolkit.getDefaultToolkit().getImage("d:/myprogram/file-mover.png");
setIconImage(iconimage);//set the icon of window to an image
setLocation(300,300); //display the window at point (300,300)

//let the window close when its close-icon is clicked
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AwtTest {
public static void main(String[] args){
new WindowShow();

}
}
Frame in Java