JAVA Unit 5
JAVA Unit 5
1
• Graphical user interface (GUI)
– Presents a user-friendly mechanism for interacting
with an application.
– Built from GUI components.
• Command Line interface (or)
Command user interface(CUI)
– In a command Line interface the commands are
entered from the keyboard.
– It is not user-friendly.
– Difficult to remember commands.
2
• Most modern applications use a GUI (pronounced
“gooey”):
• Graphical: Not just text or characters but windows,
menus, buttons, ..
• User: Person using the program
• Interface: Way to interact with the program
3
GUI elements/components include:
• Window : Portion of screen that looks as a
window.
• Menu : List of alternatives offered to user
• Button : Looks like a button that can be
pressed.
• Text fields: The user can write something in etc.
4
button menus title bar menu bar Choice box
scroll
bars
• import java.awt.*;
6
AWT class hierarchy Object
Component
Label
Button
TextArea
TextComponent
TextField Container
List
Choice
CheckBox
CheckBoxGroup
Scrollbar Window Panel ScrollPane
Canvas
MenuComponent
Frame Dialog Applet
Menu 7
Introduction to Swings
• import javax.swing.*;
8
• Commonly used classes in javax.swing package:
JButton, JTextBox, JTextArea, JPanel, JFrame, JMenu,
JLabel, …
Hierarchy of Java Swing classes
9
JFrame
Component:
• This is an abstract super class of all AWT classes.
• This class defines some basic methods that will describe about
presentation of a component.
11
Creating jfames(Method-1) (using JFrame object)
import javax.swing.*;
public class FirstSwingExample {
13
(Method-2)(by extending JFrame class)
import javax.swing.*; //main is in different class
class MyFrame extends JFrame
{
MyFrame()
{
JButton b=new JButton("click");
b.setBounds(130,100,100, 40);
add(b);
setSize(400,500);
setLayout(null);
setVisible(true);
}
}
class ExFrame
{
public static void main( String args[] )
{
new MyFrame();
}
} 14
Output:
15
(Method-2)(by extending JFrame class)
import javax.swing.*; //main is in same class
class MyFrame extends JFrame
{
MyFrame()
{
JButton b=new JButton("click");
b.setBounds(130,100,100, 40);
add(b);
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main( String args[] )
{
new MyFrame();
}
}
16
Container
The Container class is a subclass of Component.
It has additional methods that allow other
Component objects to be nested within it.
Ex:- Window, Frame, and panel are examples of
containers.
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
17
Methods defined in a class Container are:
18
Window :
Window is a type of container, which has two-dimensional
surface that can be displayed on an output device.
It does not have title bar, menu bar, borders, and
resizing corners.
Frame :
It is a type of Window with a title bar, borders, and
resizing corners.
Methods defined in a Frame class are
Layout Manager:
A Layout Manager is used to position and place
components in a Container.
19
Frames
• Frame is a window that is not contained inside another
window.
• Frame is the basis to contain other user interface
components in Java graphical applications.
• Frame’s constructors:
Frame( )
Frame(String title)
• After a frame window has been created, it will not be
visible until you call setVisible(true).
20
Frame Location
21
(0,0)
Screen
(x, y)
Frame
frameHeight screenHeight
frameWidth
screenWidth
22
creating frames:
Method-I (using Frame object)
import java.awt.*;
public class MyFrame
{
public static void main(String args[])
{
Label l=new Label("userId");
Frame f = new Frame("MyFrame");
f.add(l);
f.setSize(300,200);
f.setVisible(true);
}
}
23
Method-II (by extending Frame class)
import java.awt.*; //main is in different class
class MyFrame extends Frame
{
MyFrame()
{
super("title of Frame");
Label l=new Label("userId");
add(l);
setSize(300,200);
setVisible(true);
}
}
class ExFrame
{
public static void main( String args[] )
{
new MyFrame();
}
24
}
Method - II (by extending Frame class)
import java.awt.*; //main is in same class
class MyFrame extends Frame
{
MyFrame()
{ super("title of Frame");
Label l=new Label("userId");
add(l);
setSize(300,200);
setVisible(true);
}
public static void main( String args[] )
{
new MyFrame();
}
} 25
User-Interface Components
Label
Label()
Label(String text)
setText(String text)
getText()
26
Label import java.awt.*;
public class ExLabel extends Frame
{
public ExLabel()
{
super("Label test");
setLayout( new FlowLayout() );
Label label1 = new Label("userId");
add(label1);
setSize(300,200);
setVisible(true);
}
public static void main(String args[])
{
new ExLabel();
}
} 27
import java.awt.*;
JLabel import javax.swing.*;
public class MyLabel extends JFrame
{
public MyLabel()
{
super("JLabel");
setLayout( new FlowLayout() );
JLabel label1 = new JLabel("userId");
add(label1);
setSize(300,200);
setVisible(true);
}
public static void main(String args[])
{
new MyLabel();
}
28
}
Button
Button()
Button(String title )
getLabel()
setLabel()
29
Button import java.awt.*;
public class ExButton extends Frame
{
public ExButton()
{
super("Button test");
setLayout( new FlowLayout() );
Button button1 = new Button("no");
add(button1);
setSize(300,200);
setVisible(true);
}
public static void main(String args[])
{
new ExButton();
}
} 30
Text Components
TextField
TextField()
TextField(int columns)
TextField(String text)
TextField(String text, int columns)
setText(String)
getText()
31
import java.awt.*;
TextField public class ExTextField extends Frame
{
public ExTextField()
{
super("TextField test");
setLayout(new FlowLayout());
TextField text1 = new TextField("hello",30);
add( text1 );
setSize(300,200);
setVisible(true);
}
public static void main(String args[])
{
new ExTextField();
}
} 32
TextArea
TextArea()
TextArea(String text)
TextArea(int rows, int numChars)
TextArea(String text , int rows, int numChars)
setText(String)
getText()
33
import java.awt.*;
TextArea public class ExTextArea extends Frame
{
public ExTextArea()
{
super("TextArea test");
setLayout(new FlowLayout());
TextArea text1 = new TextArea(5,30);
add(text1);
setSize(300,200);
setVisible(true);
}
public static void main(String args[])
{
new ExTextArea();
}
} 34
Checkbox
Checkbox()
Checkbox(String text)
Checkbox(String text, boolean state)
Checkbox(String text, CheckboxGroup group,
boolean state)
getLabel() – String
setLabel() – void
getState() – boolean
setState() – boolean
35
Checkbox
import java.awt.*;
public class ExCheckbox extends Frame
{
public ExCheckbox()
{
super("Checkbox test");
setLayout(new FlowLayout());
Checkbox check1 = new Checkbox("java");
Checkbox check2 = new Checkbox("dbms");
Checkbox check3 = new Checkbox("se");
add( check1 );
add( check2 );
add( check3 );
setSize(300,200);
setVisible(true);
} ............................. 36
Checkbox Groups, Choices, and Lists
• Three types of interface components are used to
select one item from a set of possibilities.
– First is a group of connected check boxes with the property
that only one can be selected at a time.(also called radio
buttons).
– Second is choice. A choice displays only one selection, but
when the user clicks in the selection area, a pop-up menu
appears that allows the choice to be changed to a different
selection.
– A third is a List. A List is similar to a choice, but several
items out of the range can be displayed at a time.
• Use checkbox Group when the number of alternatives
is small. 37
Differences:
Select only one item Select only one item Can be selected
more than one item
Can see all items Can see only one Can see more than
item one item
38
CheckboxGroup / Radio buttons
CheckboxGroup()
Checkbox(String text, CheckboxGroup group,
boolean state)
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
39
CheckboxGroup/Radio Buttons
import java.awt.*;
public class ExRadioButton extends Frame
{
public ExRadioButton()
{
super("Radio Button test");
setLayout(new FlowLayout());
CheckboxGroup cbg = new CheckboxGroup();
Checkbox check1 = new Checkbox("java",cbg,true);
Checkbox check2 = new Checkbox("dbms",cbg,false);
Checkbox check3 = new Checkbox("se",cbg,false);
add(check1);
add(check2);
add(check3);
.....................
40
Choice
Choice()
add(String) – void ,Items are added to the list in the
order in which calls to add( ) occur.
getItemCount() – int
getItem(int) – String
remove(int) –void
getSelectedItem() – String
41
Choice
import java.awt.*;
public class ExChoice extends Frame
{
public ExChoice()
{
super("Choice Button test");
setLayout(new FlowLayout());
Choice choice1 = new Choice();
choice1.add("java");
choice1.add("dbms");
choice1.add("se");
add(choice1);
setSize(300,200);
setVisible(true);
....................
42
List
List()
List(int rows)
List(int rows, boolean multipleMode)
43
List
import java.awt.*;
public class ExList extends Frame
{
public ExList()
{
super("List test");
setLayout(new FlowLayout());
List List1 = new List(3,false);
List1.add("java");
List1.add("dbms");
List1.add("se");
List1.add("ppl");
List1.add("co");
add( List1 );
...................
44
MenuBars , Menus, MenuItems
• To create a menu bar, first create an instance of MenuBar.
Consturctor - MenuBar( )
– This class only defines the default constructor.
– a menu bar contains one or more Menu objects.
• Next, create instances of Menu ( menus)
Constructors
• Menu( )
• Menu(String menuName)
• Individual menu items are of type MenuItem.
Constructors
• MenuItem( )
• MenuItem(String itemName)
• MenuItem(String itemName, MenuShortcut keyAccel)
45
MenuBars , Menus, MenuItems
import java.awt.*;
public class ExMenubar extends Frame
{
public ExMenubar()
{
super("Menubar test");
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
Menu file = new Menu("File");
file.add(new MenuItem("New..."));
file.add(new MenuItem("Open..."));
file.add(new MenuItem("Close"));
file.add(new MenuItem("-"));
file.add(new MenuItem("Quit..."));
mbar.add(file); ..........................
46
Scrollbar
Scroll bars are used to select continuous values between a
specified minimum and maximum.
The line increment can be specified (the amount scroll bar will
move when touched the line ends).
The page increment can be specified (the amount scroll bar will
move when touched in the background area between the thumb and
the end).
47
– Scrollbar()
– Scrollbar(int style)
– Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
– Constants
• Scrollbar.VERTICAL
• Scrollbar.HORIZONTAL
• Scrollbar(Scrollbar.HORIZONTAL,0, 60, 0, 300);
• Minimum : default 0.
• Maximum : default 100
48
Scrollbar
import java.awt.*;
public class ExScrollbar extends Frame
{
public ExScrollbar()
{
super("Scrollbar test");
setLayout(new FlowLayout());
Scrollbar scroll1 = new Scrollbar(Scrollbar.HORIZONTAL);
Scrollbar scroll2 =
new Scrollbar(Scrollbar.HORIZONTAL,100, 60, 0, 300);
add( scroll1 );
add( scroll2 );
...........................
49
Panel
Which are containers, used to organize and control the layout of o
their components such as labels, buttons, text fields, and so on.
A Panel looks like a window that does not contain a title bar, m
enu bar, or border.
Panel()
Panel(LayoutManager layout)
50
Panel import java.awt.*;
public class Ex013Panel extends Frame
{
public Ex013Panel()
{
super("Panel test");
setLayout(null);
Panel pan1 = new Panel();
pan1.setSize(200,100);
pan1.setBackground(Color.red);
pan1.setLocation(50,50);
Button button1 = new Button("ok");
Button button2 = new Button("cancel");
pan1.add( button1 );
pan1.add( button2 );
add(pan1);
...................... 51
Panel Output
52
ScrollPane
It is similar to a panel.
It can hold only one Component.
If size of the component held is larger than the size of the
ScrollPane, scroll bars will be automatically generated.
It does not have a LayoutManager
ScrollPane()
53
ScrollPane
import java.awt.*;
public class ExScrollPane extends Frame
{
public ExScrollPane()
{
super("ScrollPane test");
setLayout(new FlowLayout());
ScrollPane sPane1 = new ScrollPane();
sPane1.setSize(200,100);
sPane1.setBackground(Color.red);
sPane1.setLocation(50,50);
TextArea text1 = new TextArea(300,500);
sPane1.add(text1);
add(sPane1);
......................
54
Differences between AWT & SWING
AWT SWING
1 AWT components are platform- Java swing components are platform-
dependent. independent.
2 AWT components are heavyweight. Swing components are lightweight.
55
Graphics
• Graphics object draws pixels on the screen that represent text
and other graphical shapes such as lines, ovals, rectangles,
polygons etc.
56
• Before you can do any drawing, you have to get a graphics
context object ( subclass of Graphics ).
• The best way to do that is to place all the code that does your
drawing in the paint method of a component that’s added to a
frame or panel.
57
Graphics
59
How does the paint(Graphics g) method get called?
61
Graphics methods for drawing shapes
– g.drawString (str, x, y);
• Puts string at x,y
– g.drawLine( x1, y1, x2, y2 )
• Line from x1, y1 to x2, y2
62
Example1:
import java.awt.*;
class MyGraphics extends Frame
{
MyGraphics() {
super("title of Frame");
setSize(300,200);
setVisible(true);
}
public void paint(Graphics g) {
g.drawLine(30, 30, 80, 80);
}
}
class MainGraphics
{
public static void main( String args[] )
{
new MyGraphics();
}
}
63
Output:
64
Example2:
import java.awt.*;
class Gcanvas extends Canvas{
public Gcanvas(){ setSize(200, 200); }
public void paint(Graphics g) {
g.drawLine(30, 30, 80, 80);
g.drawRect(20, 150, 100, 100);
}
}
public class Gra extends Frame
{
public Gra() {
super("Graphics");
Gcanvas g = new Gcanvas();
add(g);
setSize(400,400);
setVisible(true);
65
}
public static void main(String args[])
{
new Gra();
}
}
Output:
66
Layout Managers
• Arranges the GUI components on a container.
• Usage:
– myContainer.setLayout(new LayoutManger());
67
• Layout Managers
– Flow Layout
– Grid Layout
– Border Layout
– Card Layout
– Gridbag Layout
68
Flow Layout
• The Flow Layout manager arranges the components left-to-
right, top-to-bottom in the order they were inserted into the
container.
• When the container is not wide enough to display all the
components, the remaining components are placed in the next
row, etc.
• By default each row is centered.
• The line alignment can be:
– FlowLayout.LEFT
– FlowLayout.CENTER
– FlowLayout.RIGHT
69
Flow Layout Example
Japanese German
Spanish Portuguese
70
Flow Layout Constructors
FlowLayout(align, hgap, vgap)
align – alignment used by the manager
hgap – horizontal gaps between components
vgap – vertical gaps between components
FlowLayout(align)
align – alignment used by the manager
A default 5-unit horizontal and vertical gap
FlowLayout()
A centered alignment and a default 5-unit
horizontal and vertical gap
71
Grid Layout
• Container is divided into a grid where
components are placed in rows and columns.
72
Grid Layout Examples
73
Grid Layout Constructors
GridLayout(r, c, hgap, vgap)
r – number of rows in the layout
c – number of columns in the layout
hgap – horizontal gaps between components
vgap – vertical gaps between components
GridLayout(r, c)
r – number of rows in the layout
c – number of columns in the layout
No vertical or horizontal gaps.
GridLayout()
A single row and no vertical or horizontal
gaps.
74
Border Layout
• The Border Layout manager arranges components into five
regions: North, South, East, West, and Center.
• The Center component fills the space left in the center of the
container.
75
BorderLayout Manager
North
South
76
Border Layout Constructors
BorderLayout(hgap, vgap)
hgap – horizontal gaps between components
vgap – vertical gaps between components
BorderLayout()
No vertical or horizontal gaps.
77
Border Layout Constraints
78
CardLayouts
• CardLayout places components (usually panels) on top of
each other like a stack.
79
Constructor
-CardLayout()
Methods:-
–public void first(Container c);
–public void next(Container c);
–public void previous(Container c);
–public void last(Container c);
–public void show(Container c, String name);
New Card
First Card
add(component, name)
80
GridBagLayout
• Flexible GridBagLayout
– Components can vary in size
– Components can occupy multiple rows and columns
– Components can be added in any order
81
Column
0 1 2
Row 2
3
82
Events
83
The Delegation Event Model
• The delegation event model is a modern approach
which defines mechanisms to generate and process
events.
85
Event object
Events handling
methods
86
Action Events on Buttons
ActionEvent
actionPerformed(..)
Button ActionListener
87
Example:
public static void main(String[]
import java.awt.*; args)
import java.awt.event.*; {
public class ButtonAction new ButtonAction();
extends Frame
}
{
}
ButtonAction()
class MyActionListener
{ implements
setLayout(new ActionListener
FlowLayout()); {
Button b=new Button("ok"); public void
add(b); actionPerformed(ActionEve
b.addActionListener(new nt ae )
MyActionListener( ) ); {
setSize(200,200); System.out.println("button
setVisible(true); clicked");
} }
} 88
All Events are objects of Event Classes.
89
Closing a Frame
• When we click on the close button of a frame, frame is
not closed.
• We can close it using the below programs.
Closing a frame by implementing WindowListener interface
import java.awt.*;
import java.awt.event.*;
class FrameClose extends Frame
{
FrameClose()
{
super("Closing a frame");
setSize(300,200);
setVisible(true);
addWindowListener(new WListener());
90
}
public static void main(String args[])
{
new FrameClose();
}
}
class WListener implements WindowListener
{
public void windowActivated(WindowEvent e){ }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowIconified(WindowEvent e){ }
public void windowDeiconified(WindowEvent e){ }
public void windowDeactivated(WindowEvent e){ }
public void windowOpened(WindowEvent e){ }
}
91
public static void main(String args[])
{
new FrameClose();
}
}
class WListener implements WindowListener
{
public void windowActivated(WindowEvent e){ }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowIconified(WindowEvent e){ }
public void windowDeiconified(WindowEvent e){ }
public void windowDeactivated(WindowEvent e){ }
public void windowOpened(WindowEvent e){ }
}
92
Closing a frame by extending WindowAdapter class
import java.awt.*;
import java.awt.event.*;
class FrameClose extends Frame
{
FrameClose()
{
super("Closing a frame");
setSize(300,200);
setVisible(true);
addWindowListener(new WListener());
}
public static void main(String args[])
{
new FrameClose();
}
} 93
class WListener extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
94
Event sources
• Event source is a GUI component with which user interacts.
• Event sources may generate more than one type of event.
• A source must register listeners in order for the listeners to
receive notifications about a specific type of event.
• Each type of event listener has its own registration method.
• Here is the general form:
• public void addTypeListener(TypeListener el)
• Here, Type is the name of the event and el is a reference to the
event listener.
95
• For example,
98
Event Listeners
A listener is a class that is notified when an event
occurs.
It has two major requirements:
It must have been registered with one or more sources to receive
notifications about specific types of events
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.
The listener class must implement listener interface to
handle events.
99
Listener Interfaces
• In addition to the Event classes, there are Listener interfaces
corresponding to each Event class.
• Some of them are listed here:
ActionEvent ActionListener
MouseEvent MouseListener
MouseMotionListener
KeyEvent KeyListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ItemEvent ItemListener
TextEvent TextListener
WindowEvent WindowListener
100
ActionEvent ActionListener
101
MouseEvent MouseListener
103
KeyEvent KeyListener
104
Adapter classes
105
Adapter Class Listener Interface
MouseAdapter MouseListener
KeyAdapter KeyListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
106