Working with User Interfaces – JAVA AWT Package, Window fundamentals, Basic User Interface Components (Labels, buttons, Check boxes, Radio buttons, choice Menu or Choice Lists, Text fields, Text areas, scrolling list, scroll bars, panels and frames), Layouts (Flow, Grid, Border, Card). Event-driven programming-Event driven programs, Event handling process, Java’s event types.
JAVA Swings- Comparison between Swing and AWT, Java swing packages, Swing basic containers,Swing components, event handling using Java swing, using dialogs, Joptionpane class, input dialog boxes,Timers and Sliders, Tables, Borders for components.
JAVA AWT PACKAGES
Abstract Windowing Toolkit (AWT):The AWT contains numerous classes and methods that allow you to create and manage windows. Contains classes and interfaces required to create and manipulate GUIs in Java. The AWT classes are contained in the java.awt package. It is one of Java’s largest
packages.
AWT Classes
Window Fundamentals
The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level. The two most common windows are those derived from Panel, which is used by applets, and those derived from Frame, which creates a standard window.
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses
of Component. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting. A Component object is responsible for remembering the current foreground and background colors and the currently selected text font.
Container
The Container class is a subclass of Component. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instances of Component). This makes for a multileveled containment system. A container is responsible for laying out (that is, positioning) any components that it contains. It does this through the use of various layout managers.
Panel
The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements Container. A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border. This is why you don’t see these items when an applet is run inside a browser. When you run an applet using an applet viewer, the applet viewer provides the title and border.Other components can be added to a Panel object by its add( ) method (inherited from Container). Once these components have been added, you can position and resize them manually using the setLocation( ), setSize( ), or setBounds( ) methods defined by Component.
import java.awt.*;
import java.awt.event.*;
public class paneldemo{
public static void main(String[] args){
Panel panel = new Panel();
panel.add(new Button("Button 1"));
panel.add(new Button("Button 2"));
panel.add(new Button("Button 3"));
Frame frame = new Frame("Container Frame");
TextArea txtArea = new TextArea();
frame.add(txtArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
Window
The Window class creates a top-level window. A top-level window is not contained
within any other object; it sits directly on the desktop. Generally, you won’t create
Window objects directly. Instead, you will use a subclass of Window called Frame
.
Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. If you create a Frame object from within an applet, it will contain a warning message, such as “Java Applet Window,” to the user that an applet window has been created. This message warns users that the window they see was started by an applet and not by software running on their computer. (An applet that could masquerade as a host-based application could be used to obtain passwords and other sensitive information without the user’s knowledge.) When a Frame window is created by a program rather than an applet, a normal window is created.
Frame Windows
As mentioned, it creates a standard-style window.Here are two of Frame’s constructors:
Frame( )
Frame(String title)
The first form creates a standard window that does not contain a title. The second form creates a window with the title specified by title. Notice that you cannot specify the dimensions of the window. Instead, you must set the size of the window after it has been created.There are several methods you will use when working with Frame windows. They are examined here.
Setting the Window’s Dimensions:
The setSize( ) method is used to set the dimensions of the window. Its signature is shown here:
void setSize(int newWidth, int newHeight)
void setSize(Dimension newSize)
The new size of the window is specified by newWidth and newHeight, or by the width and height fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels.The getSize( ) method is used to obtain the current size of a window. Its signature is shown here:
Dimension getSize( )
This method returns the current size of the window contained within the width and
height fields of a Dimension object.
Hiding and Showing a Window
After a frame window has been created, it will not be visible until you call setVisible( ). Its signature is shown here:
void setVisible(boolean visibleFlag)
The component is visible if the argument to this method is true. Otherwise, it is hidden.
Setting a Window’s Title You can change the title in a frame window using setTitle( ), which has this general form:
void setTitle(String newTitle) Here, newTitle is the new title for the window.
Closing a Frame Window
When using a frame window, your program must remove that window from the
screen when it is closed, by calling setVisible(false). To intercept a window-close
event, you must implement the windowClosing( ) method of the WindowListener
interface. Inside windowClosing( ), you must remove the window from the screen.
The example in the next section illustrates this technique.
import java.awt.*;
public class MyApp1 {
public static void main (String arg[]){
Frame myFrame = new Frame("example Frame for
cosc210");
myFrame.show();
myFrame.setSize(1000,100);
}
}
SAMPLE OUTPUT
Basic User Interface Components-
LABELS
A label is an object of type Label, and it contains a string, which it displays. Labels are passive controls that do not support any interaction with the user. Label defines the following constructors:
Label( )
Label(String str)
Label(String str, int how)
The first version creates a blank label. The second version creates a label that contains
the string specified by str. This string is left-justified. The third version creates a label that contains the string specified by str using the alignment specified by how. The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.You can set or change the text in a label by using the setText( ) method. You can obtain the current label by calling getText( ). These methods are shown here:
void setText(String str)
String getText( )
For setText( ), str specifies the new label. For getText( ), the current label is returned. You can set the alignment of the string within the label by calling setAlignment( ).To obtain the current alignment, call getAlignment( ). The methods are as follows:
void setAlignment(int how)
int getAlignment( )
import java.awt.*;
public class MyApp1
{
public static void main (String arg[])
{
Frame myFrame = new Frame("example Frame for cosc210");
myFrame.show();
myFrame.setSize(300,300);
Label myLabel1 = new Label("cosc210 pass");
myFrame.add(myLabel1);
}
}
BUTTONS
A push button is a component that contains a label and that generates an event when it is pressed. Push buttons are objects of type Button. Button defines these two constructors:
Button( )
Button(String str)
The first version creates an empty button. The second creates a button that contains str as a label.
After a button has been created, you can set its label by calling setLabel( ). You can retrieve its label by calling getLabel( ). These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button.
import java.awt.*;
public class ButtonPressDemo {
public static void main(String[] args){
Button b1,b2;
Frame f = new Frame("button Example");
public class ButtonPressDemo {
public static void main(String[] args){
Button b1,b2;
Frame f = new Frame("button Example");
b1 = new Button("Bonjour");
b2 = new Button("Good morning");
f.add(b1);
f.add(b1);
f.show();
}
}
CHECK BOXES
A check box is a control that is used to turn an option on or off. It consists of a small box that can either contain a check mark or not. There is a label associated with each check box that describes what option the box represents. You change the state of a check box by clicking on it. Check boxes can be used individually or as part of a group. Check boxes are objects of the Checkbox class.Checkbox supports these constructors:
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
The first form creates a check box whose label is initially blank. The state of the check box is unchecked. The second form creates a check box whose label is specified by str.The state of the check box is unchecked. The third form allows you to set the initial state of the check box. If on is true, the check box is initially checked; otherwise, it is cleared. The fourth and fifth forms create a check box whose label is specified by str and whose group is specified by cbGroup. If this check box is not part of a group, then cbGroup must be null. (Check box groups are described in the next section.) The value of on determines the initial state of the check box. To retrieve the current state of a check box, call getState( ). To set its state, call setState( ). You can obtain the current label associated with a check box by calling getLabel( ). To set the label, call setLabel( ). These methods are as follows:
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
Here, if on is true, the box is checked. If it is false, the box is cleared. The string passed
in str becomes the new label associated with the invoking check box.
import java.awt.*;
import java.awt.event.*;
public class CheckBoxDemo{
public static void main(String[] args){
Frame frame= new Frame("Checkbox");
Checkbox check=new Checkbox("Welcome");
Checkbox check1=new Checkbox("Roseindia");
frame.add(check);
frame.add(check1);
frame.setLayout(new FlowLayout());
frame.setSize(300,200);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
} }
RADIO BUTTON
Radio buttons (javax.swing.JRadioButton) are used in groups (java.awt.ButtonGroup) where at most one can be selected.
import java.awt.*;import java.awt.event.*; public class RadioButton{ public static void main(String[] args) { Frame fm=new Frame("RedioButton Group"); Label la=new Label("What is your choice:"); fm.setLayout(new GridLayout(0, 1)); CheckboxGroup cg1=new CheckboxGroup(); fm.add(la); fm.add(new Checkbox("MATH", cg1, true)); fm.add(new Checkbox("PHYSICS", cg1, false)); fm.add(new Checkbox("CHEMISTRY", cg1, false)); fm.add(new Checkbox("ENGLISH", cg1, false)); fm.setSize(250,200); fm.setVisible(true); fm.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } });
CHOICE
The Choice class is used to create a pop-up list of items from which the user may choose. Thus, a Choice control is a form of menu. When inactive, a Choice component takes up only enough space to show the currently selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be made. Each item in the list is a string that appears as a left-justified label in the order it is added to the Choice object. Choice only defines the default constructor, which creates an empty list.To add a selection to the list, call add( ). It has this general form:
void add(String name)
Here, name is the name of the item being added. Items are added to the list in the order in which calls to add( ) occur.To determine which item is currently selected, you may call either getSelectedItem( ) or getSelectedIndex( ). These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item. getSelectedIndex( ) returns the index of the item. The first item is at index 0. By default, the first item added to the list is selected.To obtain the number of items in the list, call getItemCount( ). You can set the currently selected item using the select( ) method with either a zero-based integer index or a string that will match a name in the list. These methods are shown here:
int getItemCount( )
void select(int index)
void select(String name)
Given an index, you can obtain the name associated with the item at that index by calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
import java.awt.*;
public class ChoiceOptionExample{
public static void main(String[] args) {
Frame frame=new Frame("Choice");
Label label=new Label("What is your Choice:");
Choice choice=new Choice();
frame.add(label);
frame.add(choice);
choice.add("ROSE");
choice.add("INDIA");
public class ChoiceOptionExample{
public static void main(String[] args) {
Frame frame=new Frame("Choice");
Label label=new Label("What is your Choice:");
Choice choice=new Choice();
frame.add(label);
frame.add(choice);
choice.add("ROSE");
choice.add("INDIA");
choice.add("WELCOME");
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
}
}
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
}
}
SCROLLING LISTS
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object, which shows only the single selected item in the menu, a List object can be constructed to show any number of choices in the visible window. It can also be created to allow multiple selections. List provides these constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
The first version creates a List control that allows only one item to be selected at any one time. In the second form, the value of numRows specifies the number of entries in the list that will always be visible (others can be scrolled into view as needed). In the third form, if multipleSelect is true, then the user may select two or more items at a time. If it is false, then only one item may be selected.To add a selection to the list, call add( ). It has the following two forms:
void add(String name)
void add(String name, int index)
Here, name is the name of the item added to the list. The first form adds items to the end of the list. The second form adds the item at the index specified by index. Indexing begins at zero. You can specify –1 to add the item to the end of the list.For lists that allow only single selection, you can determine which item is currently selected by calling either getSelectedItem( ) or getSelectedIndex( ). These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item. If more than one item is selected or if no selection has yet been made, null is returned.getSelectedIndex( ) returns the index of the item. The first item is at index 0. If more than one item is selected, or if no selection has yet been made, –1 is returned.For lists that allow multiple selection, you must use either getSelectedItems( ) or getSelectedIndexes( ), shown here, to determine the current selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
getSelectedItems( ) returns an array containing the names of the currently selected items. getSelectedIndexes( ) returns an array containing the indexes of the currently selected items.
To obtain the number of items in the list, call getItemCount( ). You can set the currently selected item by using the select( ) method with a zero-based integer index. These methods are shown here:
int getItemCount( )
void select(int index)
Given an index, you can obtain the name associated with the item at that index by calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
import java.awt.*;
import java.awt.event.*;
public class ListExample{
public static void main(String[] args) {
Frame frame=new Frame("list");
List os=new List(4, true);
os.add("Windows 98/XP");
os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
Choice choice=new Choice();
frame.add(os);
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
import java.awt.*;
import java.awt.event.*;
public class ListExample{
public static void main(String[] args) {
Frame frame=new Frame("list");
List os=new List(4, true); //Only 4 items will be displayed at a time
os.add("Windows 98/XP");
os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
os.add("Mercury");
os.add("Venus");
os.add("Earth");
os.add("JavaSoft");
os.add("Mars");
os.add("Jupiter");
os.add("Saturn");
os.add("Uranus");
os.add("Neptune");
os.add("Pluto");
frame.add(os);
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
//scroll bars will be displayed only if list exceeds minimum items(here 4)
SCROLL BARS
Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of several individual parts. Each end has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the arrow. The current value of the scroll bar relative to its minimum and maximum values is indicated by the slider box (or thumb) for the scroll bar. The slider box can be dragged by the user to a new position.The scroll bar will then reflect this value. In the background space on either side of the thumb, the user can click to cause the thumb to jump in that direction by some increment larger than 1. Typically, this action translates into some form of page up and page down. Scroll bars are encapsulated by the Scrollbar class. Scrollbar defines the following constructors:
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
The first form creates a vertical scroll bar. The second and third forms allow you to specify the orientation of the scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal. In the third form of the constructor, the initial value of the scroll bar is passed in initialValue. The number of units represented by the height of the thumb is passed in thumbSize.The minimum and maximum values for the scroll bar are specified by min and max. If you construct a scroll bar by using one of the first two constructors, then you need to set its parameters by using setValues( ), shown here, before it can be used:
void setValues(int initialValue, int thumbSize, int min, int max)
The parameters have the same meaning as they have in the third constructor just described. To obtain the current value of the scroll bar, call getValue( ). It returns the current setting. To set the current value, call setValue( ). These methods are as follows:
int getValue( )
void setValue(int newValue)
Here, newValue specifies the new value for the scroll bar. When you set a value, the slider box inside the scroll bar will be positioned to reflect the new value. You can also retrieve the minimum and maximum values via getMinimum( ) and getMaximum( ), shown here:
int getMinimum( )
int getMaximum( )
They return the requested quantity.By default, 1 is the increment added to or subtracted from the scroll bar each time it is scrolled up or down one line. You can change this increment by calling
setUnitIncrement( ). By default, page-up and page-down increments are 10. You can change this value by calling setBlockIncrement( ). These methods are shown here:
void setUnitIncrement(int newIncr)
void setBlockIncrement(int newIncr)
import java.awt.*;
import java.awt.event.*;
public class scrollbarExample{
public static void main(String[] args) {
Frame frame=new Frame("scroll");
Scrollbar vertSB, horzSB;
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0,10);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0,10);
frame.add(vertSB);
frame.add(horzSB);
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
TEXT FIELD
The TextField class implements a single-line text-entry area, usually called an edit control. Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections. TextField is a subclass of TextComponent. TextField defines the following constructors:
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
The first version creates a default text field. The second form creates a text field that is numChars characters wide. The third form initializes the text field with the string contained in str. The fourth form initializes a text field and sets its width.TextField (and its superclass TextComponent) provides several methods that allow you to utilize a text field. To obtain the string currently contained in the text field, call getText( ). To set the text, call setText( ). These methods are as follows:
String getText( )
void setText(String str)
Here, str is the new string.The user can select a portion of the text in a text field. Also, you can select a portion of text under program control by using select( ). Your program can obtain the currently selected text by calling getSelectedText( ). These methods are shown here:
String getSelectedText( )
void select(int startIndex, int endIndex)
getSelectedText( ) returns the selected text. The select( ) method selects the characters
beginning at startIndex and ending at endIndex–1.You can control whether the contents of a text field may be modified by the user by calling setEditable( ). You can determine editability by calling isEditable( ). These methods are shown here:
boolean isEditable( )
void setEditable(boolean canEdit)
isEditable( ) returns true if the text may be changed and false if not. In setEditable( ), if canEdit is true, the text may be changed. If it is false, the text cannot be altered.There may be times when you will want the user to enter text that is not displayed,such as a password. You can disable the echoing of the characters as they are typed by calling setEchoChar( ). This method specifies a single character that the TextField will display when characters are entered (thus, the actual characters typed will not be shown). You can check a text field to see if it is in this mode with the echoCharIsSet( ) method. You can retrieve the echo character by calling the getEchoChar( ) method.These methods are as follows:
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
Here, ch specifies the character to be echoed.
import java.awt.*;
import java.awt.event.*;
public class textfieldExample{
public static void main(String[] args) {
Frame frame=new Frame("TextField");
TextField name, pass;
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?'); // will display ? while entering password
frame.add(namep);
frame.add(name);
frame.add(passp);
frame.add(pass);
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
TEXT AREA
Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT includes a simple multiline editor called TextArea. Following are the constructors for TextArea:
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)
Here, numLines specifies the height, in lines, of the text area, and numChars specifies its width, in characters. Initial text can be specified by str. In the fifth form you can specify the scroll bars that you want the control to have. sBars must be one of these values:
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ), setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in the preceding section.TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, int endIndex)
The append( ) method appends the string specified by str to the end of the current text. insert( ) inserts the string passed in str at the specified index. To replace text, call replaceRange( ). It replaces the characters from startIndex to endIndex–1, with the replacement text passed in str.Text areas are almost self-contained controls. Your program incurs virtually no management overhead. Text areas only generate got-focus and lost-focus events.Normally, your program simply obtains the current text when it is needed.
import java.awt.*;
import java.awt.event.*;
public class textareaExample{
public static void main(String[] args) {
Frame frame=new Frame("textArea");
String val = "There are two ways of constructing " +
"a software design.\n" +
"One way is to make it so simple\n" +
"that there are obviously no deficiencies.\n" +
"And the other way is to make it so complicated\n" +
"that there are no obvious deficiencies.\n\n" +
" -C.A.R. Hoare\n\n" +
"There's an old story about the person who wished\n" +
"his computer were as easy to use as his telephone.\n" +
"That wish has come true,\n" +
"since I no longer know how to use my telephone.\n\n" +
" -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea(val, 10, 30);
frame.add(text);
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
Layout Managers
All of the components that we have shown so far have been positioned by the default layout manager. A layout manager automatically arranges your controls within a window by using some type of algorithm.Each Container object has a layout manager associated with it. A layout manager is an instance of any class that implements the LayoutManager interface. The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used. Whenever a container is resized (or sized for the first time), the layout manager is used to position each of the components within it.The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager. If you wish to disable the layout manager and position components manually, pass null for layoutObj. If you do this, you will need to determine the shape and position of each component manually, using the setBounds( ) method defined by Component. Normally, you will want to use a layout manager. Each layout manager keeps track of a list of components that are stored by their names. The layout manager is notified each time you add a component to a container. Whenever the container needs to be resized, the layout manager is consulted via its minimumLayoutSize( ) and preferredLayoutSize( ) methods. Each component that is being managed by a layout manager contains the getPreferredSize( ) and getMinimumSize( ) methods. These return the preferred and minimum size required to display each component. The layout manager will honor these requests if at all possible, while maintaining the integrity of the layout policy. You may override these methods for controls that you subclass. Default values are provided otherwise. Java has several predefined LayoutManager classes, several of which are described next. You can use the layout manager that best fits your application.
FlowLayout
FlowLayout is the default layout manager. This is the layout manager that the preceding examples have used. FlowLayout implements a simple layout style, which is similar to how words flow in a text editor. Components are laid out from the upper-left corner, left to right and top to bottom. When no more components fit on a line, the next one appears on the next line. A small space is left between each component, above and below, as well as left and right. Here are the constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five pixels of space between each component. The second form lets you specify how each line is aligned. Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
These values specify left, center, and right alignment, respectively. The third form allows you to specify the horizontal and vertical space left between components in horz and vert, respectively.
import java.awt.*;
import java.awt.event.*;
public class fldemo extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("demo");
Button b=new Button("add");
Button b2=new Button("sub");
b.setSize(50,25);
b2.setSize(5,5);
f.add(b);
f.add(b2);
f.setSize(100,100);
f.show();
//f.setLayout(new FlowLayout());
f.setLayout(new FlowLayout(FlowLayout.LEFT));
//f.setLayout(new FlowLayout(FlowLayout.CENTER));
//f.setLayout(new FlowLayout(FlowLayout.CENTER));
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
TH E BorderLayout
The BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-width components at the edges and one large area in the center.The four sides are referred to as north, south, east, and west. The middle area is called the center. Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert) J
A The first form creates a default border layout. The second allows you to specify the horizontal and vertical space left between components in horz and vert, respectively.BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of add( ), which is defined by Container:
void add(Component compObj, Object region);
Here, compObj is the component to be added, and region specifies where the component
will be addedLIBRARY
import java.awt.*;
import java.awt.event.*;
public class boldemo extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("demo");
Button b=new Button("add");
Button b2=new Button("sub");
b.setSize(50,25);
b2.setSize(5,5);
f.add(b,BorderLayout.EAST);
f.add(b2,BorderLayout.WEST);
f.setSize(100,100);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
GridLayout
GridLayout lays out components in a two-dimensional grid. When you instantiate a GridLayout, you define the number of rows and columns. The constructors supported by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout. The second form creates a grid layout with the specified number of rows and columns. The third form allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. Either numRows or numColumns can be zero. Specifying numRows as zero allows for unlimited-length columns. Specifying numColumns as zero allows for unlimited-length rows.
import java.awt.*;
import java.awt.event.*;
public class gldemo extends Frame
{
public static void main(String args[])
{
Frame f=new Frame("demo");
f.setLayout(new GridLayout(2,3));
Button b=new Button("add");
Button b2=new Button("sub");
Button b3=new Button("mul");
f.add(b3);
f.add(b);
f.add(b2);
f.setSize(100,100);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
CardLayout
The CardLayout class is unique among the other layout managers in that it stores several different layouts. Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time. This can be useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input. You can prepare the other layouts and have them hidden, ready to be activated when needed. CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
The first form creates a default card layout. The second form allows you to specify the horizontal and vertical space left between components in horz and vert, respectively.Use of a card layout requires a bit more work than the other layouts. The cards are typically held in an object of type Panel. This panel must have CardLayout selected as its layout manager. The cards that form the deck are also typically objects of type Panel.Thus, you must create a panel that contains the deck and a panel for each card in the deck.Next, you add to the appropriate panel the components that form each card. You then add these panels to the panel for which CardLayout is the layout manager. Finally, you add this panel to the main applet panel. Once these steps are complete, you must provide some way for the user to select between cards. One common approach is to include one push button for each card in the deck.When card panels are added to a panel, they are usually given a name. Thus, most of the time, you will use this form of add( ) when adding cards to a panel:
void add(Component panelObj, Object name);
Here, name is a string that specifies the name of the card whose panel is specified by panelObj. After you have created a deck, your program activates a card by calling one of the following methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
Here, deck is a reference to the container (usually a panel) that holds the cards, and cardName is the name of a card. Calling first( ) causes the first card in the deck to be shown. To show the last card, call last( ). To show the next card, call next( ). To show the previous card, call previous( ). Both next( ) and previous( ) automatically cycle back to the top or bottom of the deck, respectively. The show( ) method displays the card whose name is passed in cardName.
class cardPanel extends Panel
{
Button button;
Label label;
cardPanel(card applet, String cardnumber)
{
button = new Button("Next card");
button.addActionListener(applet);
add(button);
label = new Label("This is card " + cardnumber);
add(label);
}
}
public class card extends Applet implements ActionListener
{
int index = 1;
CardLayout cardlayout;
cardPanel panel1, panel2, panel3;
public void init()
{
cardlayout = new CardLayout();
setLayout(cardlayout);
panel1 = new cardPanel(this, "one");
panel2 = new cardPanel(this, "two");
panel3 = new cardPanel(this, "three");
add("first", panel1);
add("second", panel2);
add("third", panel3);
cardlayout.show(this, "first");
}
public void actionPerformed(ActionEvent event)
{
switch(++index){
case 1:
cardlayout.show(this, "first");
break;
case 2:
cardlayout.show(this, "second");
break;
case 3:
cardlayout.show(this, "third");
break;
}
if(index == 3) index = 0;
repaint();
}
}

Event-driven Programs
• Input to event-driven programs come from event sources; sensors, input devices, objects on a web page.
• Events occur asynchronously and are placed in an event queue as they arise.
• Events are removed from the event queue and processed (“handled”) by the program’s main processing loop.
• As a result of handling an event the program may produce output or modify the value of a state variable.
• There is no predefined starting or stopping point.
• Java provides support for event-driven programming through certain classes and methods that can be used to design program interaction.
Java EventListener Class Interface
• For a program to handle an event it must be equipped with a listener that will recognize when a particular event has occurred.
• For example, for a program to be able to “hear” that a button has been selected it must send an addActionListener message to the button object.
• The EventListener class and its subclasses provide the interface for recognizing events by setting up appropriate listeners for component objects.
To respond to events we need to implement special methods called handlers.Each class of events predefines the names of the handlers that can be written for it.Handlers Required for Button, Menu, Text Typing, and Mouse Events
Events are supported by the java.awt.event package. An event is an object that describes a state change in a source.
Delegation Event Model :
Source generates an event and sends it to one or more listeners.The listener simply waits until it receives an event. Once received, the listener processes the event
JAVA’S EVENT TYPES
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
KeyEvent
MouseEvent
PaintEvent
TextEvent
WindowEvent
ActionEvent: Generated when a button is pressed, a list item is double-clicked, or a menu item is selected.
AdjustmentEvent: Generated when a scroll bar is manipulated.ComponentEvent Generated when a component is hidden, moved, resized,or becomes visible.
ContainerEvent: Generated when a component is added to or removed from a container.
FocusEvent: Generated when a component gains or loses keyboard focus.
InputEvent: Abstract super class for all component input event classes.
ItemEvent: Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselected.
KeyEvent: Generated when input is received from the keyboard.
MouseEvent :Generated when the mouse is dragged, moved, clicked,pressed, or released; also generated when the mouse enters or exits a component.
MouseWheelEvent: Generated when the mouse wheel is moved.
TextEvent: Generated when the value of a text area or text field is changed.
WindowEvent: Generated when a window is activated, closed, deactivated, deiconified,iconified, opened, or quit.
EVENT HANDLING PROCESS
Event Sources:A source is an object that generates an event.A source must register listeners in order for the listeners to receive notifications about a specific type of event.The general form of the registration method:
public void addTypeListener(TypeListener el)
Eg:
addKeyListener( )
addMouseMotionListener
public void removeTypeListener(TypeListener el)
Button Generates action events when the button is pressed.
Checkbox Generates item events when the check box is selected or deselected.Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked; generates item events when an item is selected or deselected.
Menu Item Generates action events when a menu item is selected; generates item events when a checkable menu item is selected or deselected
Scrollbar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Window Generates window events when window is activated,closed,deactivated,deiconified, iconified, opened, or quit
A listener is an object that is notified when an event occurs. It has two major requirements: First, it must have been registered with one or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event.
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden, moved, resized, or shown.
import java.awt.*;
import java.awt.event.*;
public class bdemo extends Frame implements ActionListener
TextField text1=new TextField(20);
Button b=new Button("Click Here!");
b.addActionListener(this);
public void actionPerformed(ActionEvent event)
{
String msg = new String ("Hello from Java!");
if(event.getSource()==b)
{
text1.setText(msg);
}
}
Swing Features
} Borders: Can draw borders around components in different styles using setBorder method
} Graphics Debugging: can use setDebuggingGraphicsOptions method to set up graphics debugging.
} Easy mouseless operation:easy to connect keystrokes to components
} Tooltips:setToolTipText method of Jcomponent gives components tooltip
} Easy Scrolling:can connect scrolling to different components
} New layout manager: BoxLayout and OverlayLayout layout managers.
Comparison between Swing and AWT
} Swing have 4 times user interface (UI) components as AWT
} AWT took six weeks to write, and was modeled after HTML controls and allocates one OS window per component which slows performance and use lots of memory, so called heavyweight components.
} Internet Foundation Classes(IFC) was found by Netscape as a control set for using java.
} Later SUN and Netscape produced Swing set of components the part of Java Foundation Classes(JFC)
} So JFC contains Swing and other items
} It uses fewer system resources
} Adds a lot more sophisticated components
} Lets to tailor the look and feel of a programmer
} It’s a set of packages built on top of the AWT with a number of prebuilt classes(over 250 classes and 40 UI components)
} Each UI components starts with “J “
} package javax.swing.*, introduced in Java 1.2
} Swing controls simply draws as images in their containers and don’t have an operating platform window of their own at all, so use fewer system resources. So called lightweight components.
} Swing components are derived from JComponent class which is derived from the AWT Container class
} Swing supports heavy weight classes: JFrame, JDialogue, JWindow, JApplet
} Abstract Window Toolkit (AWT) has provided platform-independent APIs for user interface components.
} In AWT, each component is rendered and controlled by a native peer component specific to the underlying windowing system.
} The AWT components are referred to as heavyweight components
} By contrast, Swing components are often described as lightweight because they do not require allocation of native resources in the operating system's windowing toolkit.
} The Swing API is generally a complementary extension of the AWT rather than a direct replacement.
} Every Swing lightweight interface ultimately exists within an AWT heavyweight component because all of the top-level components in Swing (JApplet, JDialog,JFrame, and JWindow) extend an AWT top-level container.
} The core rendering functionality used by Swing to draw its lightweight components is provided by Java 2D, another part of JFC.
Java swing packages
Swing basic containers
Refer Java - Lecture 6 – Containers.pdf
Swing components
JApplet
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must be subclasses of JApplet. JApplet is rich with functionality that is not found in Applet. For example, JApplet supports various “panes,” such as the content pane, the glass pane, and the root pane. For the examples in this chapter, we will not be using most of JApplet’s enhanced features. However, one difference between Applet and JApplet is important to this discussion, because it is used by the sample applets in this chapter. When adding a component to an instance of JApplet, do not invoke the add( ) method of the applet. Instead, call add( ) for the content pane of the JApplet object. The content pane can be obtained via the method shown here:
Container getContentPane( ).
The add( ) method of Container can be used to add a component to a content pane.Its form is shown here:
void add(comp)
Here, comp is the component to be added to the content pane.
Icons and Labels
In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image. Two of its constructors are shown here:
ImageIcon(String filename)
ImageIcon(URL url)
The first form uses the image in the file named filename. The second form uses the image in the resource identified by url.
The ImageIcon class implements the Icon interface that declares the methods
shown here:Method Description
int getIconHeight( ) Returns the height of the icon in pixels.
int getIconWidth( ) Returns the width of the icon in pixels.
void paintIcon(Component comp, Graphics g,int x, int y)
Paints the icon at position x, y on the graphics context g. Additional information about the paint
operation can be provided in comp.Swing labels are instances of the JLabel class, which extends JComponent. It can display text and/or an icon. Some of its constructors are shown here:
JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)
Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in the SwingConstants interface, along with several others used by the Swing classes.The icon and text associated with the label can be read and written by the following methods:
Icon getIcon( )
String getText( )
void setIcon(Icon i)
void setText(String s)
Here, i and s are the icon and text, respectively.The following example illustrates how to create and display a label containing both an icon and a string. The applet begins by getting its content pane. Next, an ImageIcon object is created for the file france.gif. This is used as the second argument to the JLabel constructor. The first and last arguments for the JLabel constructor are the label text and the alignment. Finally, the label is added to the content pane.
Text Fields
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It provides functionality that is common to Swing text components. One of its subclasses is JTextField, which allows you to edit one line of text. Some of its constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
Here, s is the string to be presented, and cols is the number of columns in the text field.The following example illustrates how to create a text field. The applet begins by getting its content pane, and then a flow layout is assigned as its layout manager. Next,a JTextField object is created and is added to the content pane.
Buttons
Swing buttons provide features that are not found in the Button class defined by the AWT. For example, you can associate an icon with a Swing button. Swing buttons are subclasses of the AbstractButton class, which extends JComponent. AbstractButton contains many methods that allow you to control the behavior of buttons, check boxes,and radio buttons. For example, you can define different icons that are displayed for the component when it is disabled, pressed, or selected. Another icon can be used as a rollover icon, which is displayed when the mouse is positioned over that component.The following are the methods that control this behavior:
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
Here, di, pi, si, and ri are the icons to be used for these different conditions.The text associated with a button can be read and written via the following methods:
String getText( )
void setText(String s)
Here, s is the text to be associated with the button.Concrete subclasses of AbstractButton generate action events when they are pressed. Listeners register and unregister for these events via the methods shown here:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
Here, al is the action listener.AbstractButton is a superclass for push buttons, check boxes, and radio buttons.
The JButton Class
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be associated with the push button. Some of its constructors are shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button.
Check Boxes
The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state buttons. 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)
Here, i is the icon for the button. The text is specified by s. If state is true, the check box is initially selected. Otherwise, it is not.The state of the check box can be changed via the following method:
void setSelected(boolean state)
Here, state is true if the check box should be checked.The following example illustrates how to create an applet that displays four check boxes and a text field. When a check box is pressed, its text is displayed in the text field.The content pane for the JApplet object is obtained, and a flow layout is assigned as its layout manager. Next, four check boxes are added to the content pane, and icons are assigned for the normal, rollover, and selected states. The applet is then registered to receive item events. Finally, a text field is added to the content pane.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. JA
Radio Buttons
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state buttons. Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the button is initially selected. Otherwise, it is not.Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at any time. For example, if a user presses a radio button that is in a group, any previously selected button in that group is automatically deselected.
The ButtonGroup class is instantiated to create a button group. Its default constructor
is invoked for this purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.The following example illustrates how to use radio buttons. Three radio buttons and one text field are created. When a radio button is pressed, its text is displayed in the text field. First, the content pane for the JApplet object is obtained and a flow layout is assigned as its layout manager. Next, three radio buttons are added to the content pane. Then, a button group is defined and the buttons are added to it. Finally, a text field is added to the content pane.Radio button presses generate action events that are handled by actionPerformed( ).
The getActionCommand( ) method gets the text that is associated with a radio button and uses it to set the text field.
Combo Boxes
Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBox class, which extends JComponent. A combo box normally displays one entry. However, it can also display a drop-down list that allows a user to select a different entry. You can also type your selection into the text field. Two of JComboBox’s constructors are shown here:
JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box.Items are added to the list of choices via the addItem( ) method, whose signature is shown here:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
Tabbed Panes
A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time. Tabbed panes are commonly used for setting configuration options.
Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent. We will use its default constructor. Tabs are defined via the following method:
void addTab(String str, Component comp)
Here, str is the title for the tab, and comp is the component that should be added to the tab. Typically, a JPanel or a subclass of it is added. The general procedure to use a tabbed pane in a window is outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the title of the tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the window
Scroll Panes
A scroll pane is a component that presents a rectangular area in which a component may be viewed. Horizontal and/or vertical scroll bars may be provided if necessary.Scroll panes are implemented in Swing by the JScrollPane class, which extends JComponent. Some of its constructors are shown here:
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
Here, comp is the component to be added to the scroll pane. vsb and hsb are int constants that define when vertical and horizontal scroll bars for this scroll pane are shown. These constants are defined by the ScrollPaneConstants interface. Some examples of these constants are described as follows:
Constant Description
HORIZONTAL_SCROLLBAR_ALWAYS Always provide horizontal scroll bar
HORIZONTAL_SCROLLBAR_AS_NEEDED Provide horizontal scroll bar, if needed
VERTICAL_SCROLLBAR_ALWAYS Always provide vertical scroll bar
VERTICAL_SCROLLBAR_AS_NEEDED Provide vertical scroll bar, if needed
Here are the steps that you should follow to use a scroll pane
1. Create a JComponent object.
2. Create a JScrollPane object. (The arguments to the constructor specify the component and the policies for vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the window
. Trees
A tree is a component that presents a hierarchical view of data. A user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class, which extends JComponent. Some of its constructors are shown here:
JTree(Hashtable ht)
JTree(Object obj[ ])
JTree(TreeNode tn)
JTree(Vector v)
The first form creates a tree in which each element of the hash table ht is a child node.Each element of the array obj is a child node in the second form. The tree node tn is the root of the tree in the third form. Finally, the last form uses the elements of vector v as child nodes.A JTree object generates events when a node is expanded or collapsed. The addTreeExpansionListener( ) and removeTreeExpansionListener( ) methods allow listeners to register and unregister for these notifications. The signatures of these methods are shown here:
void addTreeExpansionListener(TreeExpansionListener tel)
void removeTreeExpansionListener(TreeExpansionListener tel)
Here, tel is the listener object.The getPathForLocation( ) method is used to translate a mouse click on a specific point of the tree to a tree path. Its signature is shown here:
TreePath getPathForLocation(int x, int y)
Here, x and y are the coordinates at which the mouse is clicked. The return value is a TreePath object that encapsulates information about the tree node that was selected by the user.The TreePath class encapsulates information about a path to a particular node in a tree. It provides several constructors and methods. In this book, only the toString( ) method is used. It returns a string equivalent of the tree path.The TreeNode interface declares methods that obtain information about a tree node. For example, it is possible to obtain a reference to the parent node or an enumeration of the child nodes. The MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the parent node.The DefaultMutableTreeNode class implements the MutableTreeNode interface.It represents a node in a tree. One of its constructors is shown here:
DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or children.To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode
can be used. Its signature is shown here:
void add(MutableTreeNode child)
Here, child is a mutable tree node that is to be added as a child to the current node.Tree expansion events are described by the class TreeExpansionEvent in the javax.swing.event package. The getPath( ) method of this class returns a TreePath object that describes the path to the changed node. Its signature is shown here:
TreePath getPath( )
The TreeExpansionListener interface provides the following two methods:
void treeCollapsed(TreeExpansionEvent tee)
void treeExpanded(TreeExpansionEvent tee)
Here, tee is the tree expansion event. The first method is called when a subtree is hidden, and the second method is called when a subtree becomes visible.Here are the steps that you should follow to use a tree
1. Create a JTree object.
2. Create a JScrollPane object. (The arguments to the constructor specify the tree and the policies for vertical and horizontal scroll bars.)
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane of the applet.
Tables
A table is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position. Tables are implemented by the JTable class, which extends JComponent. One of its constructors is shown here:
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings.
Here are the steps for using a table in a window:
1. Create a JTable object.
2. Create a JScrollPane object. (The arguments to the constructor specify the table and the policies for vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the window.
event handling using Java swing
The Java Swing event model is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source. Or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source.
Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects. Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources.
The most important rule to keep in mind about event listeners is that they should execute very quickly. Because all drawing and event-listening methods are executed in the same thread, a slow event-listener method can make the program seem unresponsive and slow to repaint itself. If you need to perform some lengthy operation as the result of an event, do it by starting up another thread (or somehow sending a request to another thread) to perform the operation.
Every event-listener method has a single argument an object that inherits from the EventObject class. Although the argument always descends from EventObject, its type is generally specified more precisely. For example, the argument for methods that handle mouse events is an instance of MouseEvent, where MouseEvent is an indirect subclass of EventObject.
Events can be divided into two groups: low-level events and semantic events. Low-level events represent window-system occurrences or low-level input. Everything else is a semantic event. Examples of low-level events include mouse and key events both of which result directly from user input. Examples of semantic events include action and item events. Whenever possible, you should listen for semantic events rather than low-level events. That way, you can make your code as robust and portable as possible.
To help you avoid implementing empty method bodies, the API generally includes an adapter class for each listener interface with more than one method. For example, the MouseAdapter class implements the MouseListener interface. An adapter class implements empty versions of all its interface's methods.
Inner classes can also be useful for event listeners that implement one or more interfaces directly. You can create an inner class without specifying a name this is known as an anonymous inner class.
An EventHandler class supports dynamic generation of simple, one-statement event listeners. Probably the most common use of EventHandler is to extract a property value from the source of the event object and set this value as the value of a property of the target object.
The Java Swing event model is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source. Or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source.
Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects. Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources.
The most important rule to keep in mind about event listeners is that they should execute very quickly. Because all drawing and event-listening methods are executed in the same thread, a slow event-listener method can make the program seem unresponsive and slow to repaint itself. If you need to perform some lengthy operation as the result of an event, do it by starting up another thread (or somehow sending a request to another thread) to perform the operation.
Every event-listener method has a single argument an object that inherits from the EventObject class. Although the argument always descends from EventObject, its type is generally specified more precisely. For example, the argument for methods that handle mouse events is an instance of MouseEvent, where MouseEvent is an indirect subclass of EventObject.
Events can be divided into two groups: low-level events and semantic events. Low-level events represent window-system occurrences or low-level input. Everything else is a semantic event. Examples of low-level events include mouse and key events both of which result directly from user input. Examples of semantic events include action and item events. Whenever possible, you should listen for semantic events rather than low-level events. That way, you can make your code as robust and portable as possible.
To help you avoid implementing empty method bodies, the API generally includes an adapter class for each listener interface with more than one method. For example, the MouseAdapter class implements the MouseListener interface. An adapter class implements empty versions of all its interface's methods.
Inner classes can also be useful for event listeners that implement one or more interfaces directly. You can create an inner class without specifying a name this is known as an anonymous inner class.
An EventHandler class supports dynamic generation of simple, one-statement event listeners. Probably the most common use of EventHandler is to extract a property value from the source of the event object and set this value as the value of a property of the target object.
using dialogs
Dialog boxes are windows that typically are used to display important messages to the user of an application.
Class JOptionPane allows,
Message Dialog: is used to display a simple mesage
It has two or three buttons:
“Yes” and “No”
“Yes”, “No” and “Cancel”
“Ok” and Cancel”
Input Dialog: is used to display a prompt for inputting. This method returns a String value which is entered by you.
Confirm Dialog: ask the user for confirmation(Yes/No) by displaying message. This method returns a numeric value either 0 or 1. if u click on the “Yes” button then the method returns 1 otherwisw 0
Contains two buttons “Ok” and Cancel”
Class JOptionPane is defined in a package called javax.swing.
Methods:
showMessageDialog is a static method which requires two arguments
First argument-is the parent object in which the dialo1g box opens
Second argument- is the string to display
Third argument- is the string to display in the title bar of the dialog
Fourth argument- is a value indicating the type of message dialog to display
Types
JOptionPane.ERROR_MESSAGE
JOptionPane.INFORMATION_MESSAGE
JOptionPane.WARNING_MESSAGE
JOptionPane.QUESTION_MESSAGE
JOptionPane.PLAIN_MESSAGE
showInputDialog
Processing Timer Events
javax.swing.Timer generates equally spaced timer events Useful whenever you want to have an object updated in regular intervals Sends events to action listener
Define a class that implements the ActionListener interface
Add listener to timer
Example: a timer that counts down to zero
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.Timer; /** This program tests the Timer class.*/
public class TimerTester
{
public static void main(String[] args)
{
class CountDown implements ActionListener
{
public CountDown(int initialCount)
{
count = initialCount;
}
public void actionPerformed(ActionEvent event)
{
if (count >= 0)
System.out.println(count);
if (count == 0)
System.out.println("Liftoff!");
count--;
}
private int count;
}
CountDown listener = new CountDown(10);
final int DELAY = 1000; // Milliseconds between // timer ticks
Timer t = new Timer(DELAY, listener);
t.start();
JOptionPane.showMessageDialog(null, "Quit?");
System.exit(0);
}
}
Borders for components
The javax.swing.border package provides 9 classes and 1 interface that implement bordr and border styles.
Interfaces:
Border – with method to render border around a swing component.
Classes:
AbstractBorder:
Subclass of Object and implements Border and java.io.Serializable interface
BevelBorder
Subclass of AbtsractBorder that implements a two-line bevel border
ComponentBorder
Subclass of AbtsractBorder that combines two Border objects into a single border
EmptyBorder
Subclass of AbtsractBorder that implements an empty sapceless border and java.io.Serializable interface
EtchedBorder
Subclass of AbtsractBorder that implements an etched border, which cud be etched either in or out
LineBorder:
Subclass of AbtsractBorder that draws a lene border around an object. The line thickness and color of the border may be specified.
MatteBorder:
Subclass of EmptyBorder that implements a matte-like border. The border can consists of a specified color or a javax.swing.Icon object.
SoftBevelBorder:
Subclass of BevelBorder that implements a bevel border with softened(rounded) corners. The beveling can be raised or lowered.
TitledBorder:
Subclass of AbtsractBorder that specifies a text tile at a specified position on the border.
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));
Here's a picture of the container, which contains a label component. The black line drawn by the border marks the edge of the container.
The following pictures show an application called
BorderDemo that displays the borders Swing provides.
The next picture shows some matte borders. When creating a matte border, you specify how many pixels it occupies at the top, left, bottom, and right of a component. You then specify either a color or an icon for the matte border to draw. You need to be careful when choosing the icon and determining your component's size; otherwise, the icon might get chopped off or have mismatch at the component's corners.

The next picture shows titled borders. Using a titled border, you can convert any border into one that displays a text description. If you don't specify a border, then a look-and-feel-specific border is used. For example, the default titled border in the Java look and feel uses a gray line, and the default titled border in the Windows look and feel uses an etched border. By default, the title straddles the upper left of the border, as shown at the top of the following figure.

The next picture shows compound borders. With compound borders, you can combine any two borders, which can themselves be compound borders.

The code that follows shows how to create and set the borders you saw in the preceding figures
//Keep references to the next few borders, for use in titles
//and compound borders.
Border blackline, etched, raisedbevel, loweredbevel, empty;
blackline = BorderFactory.createLineBorder(Color.black);
etched = BorderFactory.createEtchedBorder();
raisedbevel = BorderFactory.createRaisedBevelBorder();
loweredbevel = BorderFactory.createLoweredBevelBorder();
empty = BorderFactory.createEmptyBorder();
//Simple borders
jComp2.setBorder(blackline);
jComp3.setBorder(raisedbevel);
jComp4.setBorder(loweredbevel);
jComp5.setBorder(empty);
//Matte borders
ImageIcon icon = new ImageIcon("images/left.gif"); //20x22
jComp6.setBorder(BorderFactory.createMatteBorder(
-1, -1, -1, -1, icon));
jComp7.setBorder(BorderFactory.createMatteBorder(
1, 5, 1, 1, Color.red));
jComp8.setBorder(BorderFactory.createMatteBorder(
0, 20, 0, 0, icon));
//Titled borders
TitledBorder title1, title2, title3, title4, title5;
title1 = BorderFactory.createTitledBorder("title");
jComp9.setBorder(title1);
title2 = BorderFactory.createTitledBorder(
blackline, "title");
title2.setTitleJustification(TitledBorder.CENTER);
jComp10.setBorder(title2);
title3 = BorderFactory.createTitledBorder(
etched, "title");
title3.setTitleJustification(TitledBorder.RIGHT);
jComp11.setBorder(title3);
title4 = BorderFactory.createTitledBorder(
loweredbevel, "title");
title4.setTitlePosition(TitledBorder.ABOVE_TOP);
jComp12.setBorder(title4);
title5 = BorderFactory.createTitledBorder(
empty, "title");
title5.setTitlePosition(TitledBorder.BOTTOM);
jComp13.setBorder(title5);
//Compound borders
Border compound1, compound2, compound3;
Border redline = BorderFactory.createLineBorder(Color.red);
//This creates a nice frame.
compound1 = BorderFactory.createCompoundBorder(
raisedbevel, loweredbevel);
jComp14.setBorder(compound1);
//Add a red outline to the frame.
compound2 = BorderFactory.createCompoundBorder(
redline, compound1);
jComp15.setBorder(compound2);
//Add a title to the red-outlined frame.
compound3 = BorderFactory.createTitledBorder(
compound2, "title",
TitledBorder.CENTER,
TitledBorder.BELOW_BOTTOM);
jComp16.setBorder(compound3);
Sliders
JSlider class (defined in javax.swing package)
-An object of the JSlider class allows a user to specify a numeric value within a bounded range.
-It can be presented either vertically or horizontally.
-It can have optional tick marks.
-It can have labels indicating the range of values.
We can instantiate an object of JSlider as:
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 255, 100);
Here the first parameter is an orientation, it can be either horizontal or vertical. Its default is horizontal orientation.
The second parameter is the minimum of the numeric range.
The third parameter is the maximum of the numeric range.
The forth parameter is the initial chosen numeric value. Its default is the average of minimum and maximum.
void setMajorTickSpacing(int n)
-> This method sets the major tick spacing
void setMinorTickSpacing(int n)
-> This method sets the minor tick spacing.
void setPaintTicks(boolean b)
-> This method determines whether tick marks are painted on the slider.
void setPaintLabels(boolean b)
-> This method determines whether labels are painted on the slider

A listener class for JSlider needs to implement ChangeListener interface (javax.swing package).The ChangeListener interface has an abstract method,
public void stateChanged(ChangeEvent event)
This is where we define an action to be taken in case a user moves the slider to specify a different numeric value from the initial one.
A GUI Example using JSlider:
The following example pops up a GUI application where a User can choose a numeric value for Red, and the panel will Show the color that corresponds to the chosen red color value.Note that green and blue color values are set to zero.
------------------------------------------------------------------------------
import java.awt.*;
import javax.swing.*;
public class SliderExample
{
//-----------------------------------------------------------------
// Presents up a frame with a control panel and a panel that
// changes color as the sliders are adjusted.
//-----------------------------------------------------------------
public static void main (String[] args)
{
JFrame frame = new JFrame ("View Colors");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SliderPanel());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
//*******************************************************
// SliderPanel class represents the slider control panel to change
// the degree of Red color in the panel.
//*******************************************************
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*; //to use ChangeListener and ChangeEvent
public class SliderPanel extends JPanel
{
private JPanel colorPanel;
private JSlider rSlider;
private JLabel rLabel;
private int red;
//-----------------------------------------------------------------
// Sets up a slider, a label, and a panel that will display a color
//-----------------------------------------------------------------
public SliderPanel ()
{
red = 100; //default red value
rLabel = new JLabel("Red value: " + red);
rLabel.setAlignmentX (Component.CENTER_ALIGNMENT);
rSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, red);
rSlider.setMajorTickSpacing (50);
rSlider.setMinorTickSpacing (10);
rSlider.setPaintTicks (true);
rSlider.setPaintLabels (true);
rSlider.setAlignmentX (Component.CENTER_ALIGNMENT);
rSlider.addChangeListener (new SliderListener());
colorPanel = new JPanel();
colorPanel.setPreferredSize (new Dimension (100, 50));
colorPanel.setBackground (new Color (red, 0, 0));
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
add(rLabel);
add(rSlider);
add (colorPanel);
}
//**********************************************
// Represents the listener for the slider.
//**********************************************
private class SliderListener implements ChangeListener
{
//--------------------------------------------------------------
// Gets the value of each slider, then updates the label and
// the color panel.
//--------------------------------------------------------------
public void stateChanged (ChangeEvent event)
{
red = rSlider.getValue();
rLabel.setText ("Red value: " + red);
colorPanel.setBackground (new Color (red, 0, 0));
}
}
}

Joptionpane class
JOptionPane Contains classes used for a graphical user interface (GUI) Facilitates data entry and data output. class JOptionPane contains methods that display a dialog box. The JOptionPane class provides static methods to display each type of dialog box.
Static methods in the JOptionPane class let you easily create modal dialogs to show messages (JOptionPane.showMessageDialog),to ask for confirmation (JOptionPane.showConfirmDialog), to let the user enter text or to choose among predefined options (JOptionPane.showInputDialog), or to choose among a variety of buttons (JOptionPane.showOptionDialog). Each of these methods either returns an int specifying which button was pressed, or a String specifying the option selected.
Following are the four standard varieties of confirmation dialogs available via JOptionPane.showMessageDialog, shown with the Windows LAF. Note that they were interactively created via JOptionPaneExamples.java, which lets you interactively choose among the various dialog types and options

All dialogs are modal. Each
showXxxDialog method blocks the current thread until the user's interaction is complete
Parameters:
The parameters to these methods follow consistent patterns:
The parameters to these methods follow consistent patterns:
parentComponent
Defines the Component that is to be the parent of this dialog box. It is used in two ways: the Frame that contains it is used as the Frame parent for the dialog box, and its screen coordinates are used in the placement of the dialog box. In general, the dialog box is placed just below the component. This parameter may be null, in which case a default Frame is used as the parent, and the dialog will be centered on the screen (depending on the L&F).
A descriptive message to be placed in the dialog box. In the most common usage, message is just a String or String constant. However, the type of this parameter is actually Object. Its interpretation depends on its type:
Object[]
An array of objects is interpreted as a series of messages (one per object) arranged in a vertical stack. The interpretation is recursive -- each object in the array is interpreted according to its type.
Component
The Component is displayed in the dialog.
Icon
The Icon is wrapped in a JLabel and displayed in the dialog.
others
The object is converted to a String by calling its toString method. The result is wrapped in a JLabel and displayed.
messageType
Defines the style of the message. The Look and Feel manager may lay out the dialog differently depending on this value, and will often provide a default icon. The possible values are:
· ERROR_MESSAGE
· INFORMATION_MESSAGE
· WARNING_MESSAGE
· QUESTION_MESSAGE
· PLAIN_MESSAGE
optionType
Defines the set of option buttons that appear at the bottom of the dialog box:
· DEFAULT_OPTION
· YES_NO_OPTION
· YES_NO_CANCEL_OPTION
· OK_CANCEL_OPTION
You aren't limited to this set of option buttons. You can provide any buttons you want using the options parameter.
options
A more detailed description of the set of option buttons that will appear at the bottom of the dialog box. The usual value for the options parameter is an array of Strings. But the parameter type is an array of Objects. A button is created for each object depending on its type:
Component
The component is added to the button row directly.
Icon
A JButton is created with this as its label.
other
The Object is converted to a string using its toString method and the result is used to label a JButton.
icon
A decorative icon to be placed in the dialog box. A default value for this is determined by the messageType parameter.
title
The title for the dialog box.
initialValue
The default selection (input value).
When the selection is changed, setValue is invoked, which generates a PropertyChangeEvent.
If a JOptionPane has configured to all input setWantsInput the bound property JOptionPane.INPUT_VALUE_PROPERTY can also be listened to, to determine when the user has input or selected a value.
When one of the showXxxDialog methods returns an integer, the possible values are:
- YES_OPTION
- NO_OPTION
- CANCEL_OPTION
- OK_OPTION
- CLOSED_OPTION
Examples:
Show an error dialog that displays the message, 'alert':
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
Show an internal information dialog with the message, 'information':
JOptionPane.showInternalMessageDialog(frame, "information",
"information", JOptionPane.INFORMATION_MESSAGE);
Show an information panel with the options yes/no and message 'choose one':
JOptionPane.showConfirmDialog(null,
"choose one", "choose one", JOptionPane.YES_NO_OPTION);
Show an internal information dialog with the options yes/no/cancel and message 'please choose one' and title information:
JOptionPane.showInternalConfirmDialog(frame,
"please choose one", "information",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
Show a warning dialog with the options OK, CANCEL, title 'Warning', and message 'Click OK to continue':
Object[] options = { "OK", "CANCEL" };
JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
Show a dialog asking the user to type in a String:
String inputValue = JOptionPane.showInputDialog("Please input a value");
Show a dialog asking the user to select a String:
Object[] possibleValues = { "First", "Second", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
Direct Use:
To create and use an JOptionPane directly, the standard pattern is roughly as follows:
To create and use an JOptionPane directly, the standard pattern is roughly as follows:
JOptionPane pane = new JOptionPane(arguments);
pane.set.Xxxx(...); // Configure
JDialog dialog = pane.createDialog(parentComponent, title);
dialog.show();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return CLOSED_OPTION;
//If there is not an array of option buttons:
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return CLOSED_OPTION;
}
//If there is an array of option buttons:
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return CLOSED_OPTION;






0 comments:
Post a Comment