Unit 5.1
Unit 5.1
scroll
bars
The AWT contains several classes and methods that allow you to
create and manage windows.
TextComponent
TextField
List
Container
Choice
CheckBox
CheckBoxGroup Panel ScrollPane
Window
Scrollbar
Canvas
Frame Dialog Applet
MenuComponent
MenuItem MenuBar
Menu
Component: (java.awt)
Component is an abstract class that encapsulates all of the attributes of a visual
component.
It is a super class of all user interface classes.
A component is something that can be displayed on a two-dimensional screen
and with which the user can interact.
Attributes of a component include a size, a location, foreground and background
colors, whether or not visible etc.,
The default layout manager for a panel is the FlowLayout layout manager.
Window: (java.awt)
The Window class creates a top-level window.
Layout Manager:
A manager is used to position and place components in a Container.
Event Handling
The Delegation Event Model
It defines standard and consistent mechanisms to generate and process events.
The listener simply waits until it receives an event. Once received, the listener
processes the event and then returns.
When an event occurs, the event source invokes the appropriate method
defined by the listener and provides an event object as its argument.
In the delegation event model, listeners must register with a source in order
to receive an event notification.
The Delegation Event Model Action Events on Buttons
Event Object
ActionEvent
For example, the method that registers a keyboard event listener is called
addKeyListener( ).
Event Listeners
A listener is an object that is notified when an event occurs.
Any object may receive and process one or both of these events if it provides
an implementation of this interface.
Event Classes
EventObject is a superclass of all events which is defined in java.util package.
ActionEvent ActionListener
MouseEvent MouseListener
MouseMotionListener
KeyEvent KeyListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ItemEvent ItemListener
TextEvent TextListener
WindowEvent WindowListener
The ActionListener Interface
This interface defines the actionPerformed() method that is invoked when an
action event occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
Adapter classes are useful when you want to receive and process only some of
the events that are handled by a particular event listener interface.
You can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which you are interested.
Table 20-4 lists the commonly used adapter classes in java.awt.event and
corresponding interfaces.
Frame( )
Frame(String title)
After a frame window has been created, it will not be visible until you
call setVisible( true).
Frame Location
By default, a frame is displayed in the upper- left corner of the screen.
(0,0)
Screen
(x, y)
Frame
frameHeight screenHeight
frameWidth
screenWidth
//Method 1
import java.awt.*;
public class MyFrame{
public static void main( String args[]){
Frame f = new Frame("MyFrame");
f.setSize(300,200);
f.setVisible(true);
}
}
//Method 2
import java.awt.*;
public class MyFrame extends Frame{
MyFrame(){
super(“title of Frame”);
setSize(300,200);
setVisible(true);
}
}
class ExFrame{
public static void main( String args[]){
new MyFrame();
}
}
//Method 3
import java.awt.*;
public class MyFrame extends Frame{
MyFrame(){
super(“title of Frame”);
setSize(300,200);
setVisible(true);
}
public static void main( String args[]){
new MyFrame();
}
}
User interface components
…
Label
Labels are passive controls that do not support any interaction with the
user.
Constructors
Label()
Label( String text )
Label( String text , int alignment )
Alignment Constants
Label.LEFT , Label.RIGHT , Label.CENTER
Methods
void setText(String text)
String getText()
void setAlignment(int alignment)
int getAlignment()
//Label Example
import java.awt.*;
public class ExLabel extends Frame
{
public ExLabel()
{
super("Label test");
Label label1 = new Label(“Enter User Name");
add( label1 );
setSize(300,200);
setVisible(true);
}
public static void main( String args[] )
{
new ExLabel();
}
}
Button
Constructors
Button()
Button(String title )
Methods
getLabel()
setLabel()
import java.awt.*; import java.awt.event.*; import java.applet.*;
/* <applet code="ButtonDemo" width=250 height=150> </applet>*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "“; Button yes, no, maybe;
public void init() {
yes = new Button("Yes"); no = new Button("No");
maybe = new Button("Undecided");
add(yes); add(no); add(maybe);
yes.addActionListener(this); no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
} } }
Checkbox
Constructors
Checkbox()
Checkbox(String text)
Checkbox(String text , boolean state)
Checkbox(String text , CheckboxGroup group , boolean state)
Methods
String getLabel()
void setLabel()
boolean getState()
void setState()
CheckboxGroup, Choice and List
Three types of interface components are used to allow the user to select
one item from a large number of possibilities.
Second is Choice.
Constructors
CheckboxGroup()
Checkbox(String text , CheckboxGroup group , boolean state)
Methods
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
Choice
Constructors
Choice()
Methods
void add(String) – To add items to the list
String getItem(int)
String getSelectedItem()
void select(int index)
void select(String name)
List
Constructors
List()
List(int rows)
List(int rows, boolean multipleMode)
Methods
void add(String) //To add item to the end of the list
void add(String, int index) //To add item at an specified index
int getItemCount() //To get the count of items in the list
String getItem(int) //To get the specified item from the list
void remove(int) //To remove the item form the list
String getSelectedItem() //To get selected item from the list
TextField
Constructors
TextField()
void setText(String)
TextField(int columns)
TextField(String text)
TextField(String text, int columns)
Methods
void setText(String)
String getText()
void setEchoChar(char) //To enter text that is not displayed
void setEditable(bolean)//if false, text cann’t be modified
//TextField Example
import java.awt.*; import java.awt.event.*; import java.applet.*;
/*<applet code="TextFieldDemo" width=380 height=150></applet>*/
public class TextFieldDemo extends Applet implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(1);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep); add(name); add(passp); add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}
TextArea
Constructors
TextArea()
TextArea(String text)
TextArea(int rows, int numChars)
TextArea(String text , int rows, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)
sBars must be one of these values:
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Methods
void append(String)
void setText(String)
String getText()
void setEditable(boolean)
void insert(String str, int index)
// Demonstrate TextArea.
import java.awt.*; import java.applet.*;
/*<applet code="TextAreaDemo" width=300 height=250></applet>*/
public class TextAreaDemo extends Applet {
public void init() {
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++)";
The line increment can be specified( the amount scroll bar will move
when it is touched in the line ends).
The page increment can be specified ( the amount scroll bar will move
when it is touched in the background area between the thumb and the
end).
Constructors
Scrollbar()
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
Constants
Scrollbar.VERTICAL
Scrollbar.HORIZONTAL
Methods
getValue()
setValue(int newValue);
void setUnitIncrement(int newIncr)
void setBlockIncrement(int newIncr)
int getMinimum( )
int getMaximum( )
They are similar to frame windows, except that dialog boxes are always
child windows of a top-level window.
Also, dialog boxes don’t have menu bars. In other respects, dialog boxes
function like frame windows.
You can add controls to them, for example, in the same way that you add
controls to a frame window.)
When a modal dialog box is active, you cannot access other parts of your
program until the dialog box is closed.
When a modeless dialog box is active, you can access other parts of your
program.
Constructors
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)
d.pack();
d.setVisible(true);
}
public static void main(String args[]){
new ExDialog();
}
}
Canvas
A Canvas is a two-dimensional area used to draw some shapes on it using the
Graphics.
Constructors
Canvas()
Methods
setSize(int width, int height)
setBackground(Color )
import java.awt.*;
It is recommended that you place the user interface components in panels and
Panel()
Panel(LayoutManager layout)
import java.awt.*;
public class ExPanel extends Frame{
public ExPanel(){
setLayout(new FlowLayout());
Panel pan1 = new Panel();
pan1.setSize(200,100);
pan1.setBackground(Color.red);
pan1.setLocation(50,50);
add( pan1 );
If size of the component held is larger than the size of the ScrollPane,
Scroll bars will be automatically generated.
Constructors
ScrollPane()
import java.awt.*;
public class ExScrollPane extends Frame{
public ExScrollPane(){
ScrollPane sPane1 = new ScrollPane();
sPane1.setSize(200,100);
sPane1.setBackground(Color.red);
sPane1.setLocation(50,50);
Panel pan1 = new Panel();
TextArea text1 = new TextArea(300,500);
pan1.add( text1 );
sPane1.add( pan1 );
add( sPane1 );
setSize(200,300);
setVisible(true);
}
public static void main(String args[]){
new ExScrollPane();
}
}
Graphics
Graphics object draws pixels on the screen that represent text and other
graphical shapes such as lines, ovals, rectangles, polygons etc.
It is needed if you do any drawing or painting other than just using standard
GUI components.
You can cause the paint method to be called at any time by calling
the
component’s repaint() method.
class myFrame extends Frame{
……..
……..
public void paint(Graphics g){
g.drawOval(x1,y1,width,height);
……
}
}
The repaint() method will do two things:
1. It calls update(Graphics g), which writes over the old drawing in background
color (thus erasing it).
x
Java coordinate system ( 0,0)
(x,y)
y
Graphics methods for drawing shapes
g.drawString (str, x, y); //Puts string at x,y
width
(x, y)
drawOval parameters
height
width
g.drawOval(x1, y1, width, height)
//Draws an oval with specified width and height. The bounding
rectangle’s top left corner is at the coordinate (x,y).The oval
touches all four sides all four sides of the bounding rectangle.
g.setColor(Color.RED)
//Sets color, it is remain active until new color is
set.
g.drawArc(x1, y1, width, height, startAngle,arcAngle)
//Draws an arc relative to the bounding rectangle’s top-left
coordinates with the specified width and height. The arc
segment is drawn starting at startAngle and sweeps arcAngle
degrees.
90 90
180 0 180 0
270 270
To select a new font, you must first construct a Font object that
describes that font.
Font(String fontName, int fontStyle, int pointSize)
//Here, fontName specifies the name of the desired
font.
Types:
Flow Layout Border Layout Grid Layout
Card Layout Gridbag Layout
When the container is not wide enough to display all the components,
the remaining components are placed in the next row, etc.
Japanese German
Spanish Portuguese
FlowLayout(align)
align – alignment used by the manager. A default 5-unit horizontal and
vertical gap.
Components in the North and South are set to their natural heights and
horizontally stretched to fill the entire width of the container.
Components in the East and West are set to their natural widths and
stretched vertically to fill the entire width of the container.
The Center component fills the space left in the center of the container.
North
South
To set BorderLayout:
add( new Button(“ok”), BorderLayout.NORTH);
Border Layout Constructors
BorderLayout()
//No vertical or horizontal gaps.
BorderLayout(hgap, vgap)
//hgap – horizontal gaps between components
//vgap – vertical gaps between components
Grid Layout
Container is divided into a grid where components are placed in
rows and columns.
Example
Grid Layout Constructors
GridLayout()
//A single row and no vertical or horizontal gaps.
GridLayout(r, c)
//r – number of rows in the layout
//c – number of columns in the layout
//No vertical or horizontal gaps.
We can put a cards on top using another control by using the methods
next(), previous(), first(), last(), and show().
Constructor: CardLayout()
Methods:
public void first(Container parent);
public void next(Container parent);
public void previous(Container parent);
public void last(Container parent);
public void show(Container parent, String name);
New Card
First Card
add(component, name)
import java.awt.*; import java.awt.event.*;
public class CardLayoutDemo extends Frame implements ActionListener, MouseListener {
Checkbox winXP, winVista, solaris, mac;
Button Win, Other;
Panel osCards;
CardLayout cardLO;
public CardLayoutDemo(){
setLayout(new BorderLayout());
cardLO = new CardLayout();
Panel tabs=new Panel();
Win = new Button("Windows");
Other = new Button("Other");
tabs.add(Win);
tabs.add(Other);
add(tabs,BorderLayout.NORTH);
osCards = new Panel();
osCards.setLayout(cardLO); // set panel layout to card layout
Panel winPan = new Panel();
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
// add Windows check boxes to a panel
winPan.setBackground(Color.CYAN);
winPan.add(winXP);
winPan.add(winVista);
// Add other OS check boxes to a panel
Panel otherPan = new Panel();
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
otherPan.setBackground(Color.RED);
otherPan.add(solaris);
otherPan.add(mac);
Win.addActionListener(this);
Other.addActionListener(this);
Example:
setLayout(gridbag);
Setting Constraints for Components
For each component that you add to the gridbag layout, you must first
set an instance of the GridBagContraints class.
Row 2
3
GridBagConstraints Data Members
The following are the constraints to control the component:
gridx, gridy, gridwidth, gridheight, weightx, weighty, ipadx, ipady , fill