Chapter 3 GUI
Chapter 3 GUI
CHAPTER ONE
Introduction to Abstract Window Toolkit (AWT)
&
Swings
GUIs are built from GUI components. These are sometimes called controls or
widgets—short for window gadgets.
A GUI component is an object with which the user interacts via the mouse, the
keyboard or another form of input, such as voice recognition.
There are two main sets of visual components and containers for user interface
design in JAVA:
2. Swing
AWT
Java‘s Abstract Window Toolkit ( AWT ) provides classes and other tools for
building programs that have a graphical user interface.
AWT is heavyweight i.e. its components are using the resources of OS.
AWT Components appear in the native GUI of the underlying operating system.
Typical components include items such as buttons, scrollbars, and text fields,
labels etc.
Components allow the user to interact with the program and provide the user
with visual feedback about the state of the program.
You must use frame, dialog or another window for creating a window.
Frame defines a top-level Window with Borders, Title and Menu Bar.
Frames are more commonly used than Windows
[Link](100,100);
[Link](10,10);
[Link](true);
Creating a Graphical User Interface
Designing a graphical user interface involves creating components, putting them into
containers, and arranging for the program to respond to events.
12
Frames
13
Creating a Frame
14
1. By extending Frame class
import [Link].*;
public class FrameExample1 extends Frame {
public FrameExample1(){
setTitle("My first Frame ");
setSize(400,500);
setLocation(50, 75);
setVisible(true);
}
public static void main(String args[]){
FrameExample1 ob=new FrameExample1();
}
15
}
2. By creating instance of Frame class
import [Link].*;
public class FrameExample2 {
public FrameExample2(){
Frame f = new Frame(―My first Frame");
[Link](400, 500);
[Link](50, 75);
[Link](true);
}
public static void main(String[] args)
{
FrameExample2 ob=new FrameExample2();
}
} 16
Creating a Frame (…cont’d)
Clicking on the Close button has no effect, because there‘s no action associated
with that button.
The frame will have be closed the hard way, by killing the program.
As with the other AWT components, the appearance of a frame depends on the
platform.
17
The Frame Class
Frames are created using one of the constructors in the Frame class.
One constructor takes a single argument (the title to be displayed at the top of
the frame):
Although the Frame object now exists, it‘s not visible on the screen.
Before making the frame visible, a method should be called to set the size of
the frame.
[Link](50, 75);
[Link](width, height);
If a program fails to call setSize or pack before displaying a frame, it will
assume a default size.
20
Frame Methods (…cont’d)
[Link] will contain f‘s width. [Link] will contain f‘s height.
21
Frame Methods (…cont’d)
The setVisible method controls whether or not a frame is currently visible on the
screen.
Calling it with false as the argument makes the frame disappear from the screen:
[Link](false);
The Frame object still exists; it can be made to reappear later by calling setVisible
again.
22
Adding Components to a Frame
To add a component to a frame (or any kind of container), the add method is
used.
add belongs to the Container class, so it‘s inherited by Frame and the other
container classes.
add(b);
23
Panels
The Panel is the container that doesn't contain title bar and menu bars.
It can have other components like button, textfield etc.
Panel aPanel = new Panel();
[Link](new Button("Ok"));
[Link](new Button("Cancel"));
OK
Problem: the parameters provided to those methods are defined in terms of pixels. Pixel
sizes may be different (depending on the platform) so the use of those methods tends to
produce GUIs which will not display properly on all platforms.
Each layout manager has its own particular rules governing how the
components will be arranged.
A layout manager attempts to adjust the layout as components are added and
as containers are resized.
A. FlowLayout
B. BorderLayout
C. GridLayout
D. CardLayout
E. GridBagLayout
• [Link]
• [Link]
• [Link]
2)FlowLayout(align)
align – alignment used by the manager
A default 5-unit horizontal and vertical gap.
import [Link].*;
North
South
Border Layout Constructors
1)BorderLayout(hgap, vgap)
hgap – horizontal gaps between components
vgap – vertical gaps between components
2)BorderLayout()
No vertical or horizontal gaps.
import [Link].*;
public class AWT1 {
public static void main(String[] args) {
[Link](400,500);
[Link](true);
}
}
Grid Layout
The GridLayout class divides the region into a grid of equally sized rows and
columns.
Components are added left-to-right, top-to-bottom.
The number of rows and columns is specified in the constructor for the
LayoutManager.
You cannot skip a position or specify an exact position for a component
You can add a blank label to a grid position and give the illusion of skipping a
position
Grid Layout Constructors
1)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
2)GridLayout(r, c)
r – number of rows in the layout
c – number of columns in the layout
No vertical or horizontal gaps.
3)GridLayout()
A single row and no vertical or horizontal gaps.
import [Link].*;
public class AWT1 {
public static void main(String[] args) {
[Link](400,500);
[Link](true);
}
}
What if I don’t want a LayoutManager?
2) Menu: Menu holds the menu items. Menu is added to frame with add() method. A sub-
menu can be added to Menu.
Menubars(…contd’d)
3) MenuItem: MenuItem displays the actual option user can select. Menu items
are added to menu with method addMenuItem(). A dull-colored line can be
added in between menu items with addSeparator() method.
This mechanism have the code which is known as event handler that is
executed when an event occurs.
This model defines the standard mechanism to generate and handle the events.
Java Event Handling(…cont’d)
Delegation Event Model
Concept:- A source generates an event and sends it to one or more listeners.
Listener waits until it receives an event.
Once received, the listener processes the event and then returns.
Application logic that processes the event is completely separated from the user
interface that generates the event.
In this model, listener must register with a source in order to receive an event
notification.
Events are supported by the [Link] package.
Java Event Handling(…cont’d)
Java Event Mechanism consists of three objects:
a. An event source
b. An event object
Event sources create event objects, and deliver them to event listeners.
Event object is the medium used by the event source to deliver relevant
information about a change in state to the event listeners.
Java Event Handling(…cont’d)
Event Object
At a minimum, an event object contains a reference to the object that caused
the event (i.e the event source).
Java Event Handling(…cont’d)
Event Source
An event source is a component or object that generates events.
This occurs when the internal state of that object changes in some way.
Sources may generate more than one type of event. E.g :GUI button.
A source must register listeners in order for the listeners to receive notifications
,about a specific type of event.
It must have been registered with one or more source to receive notifications about specific
types of event.
Each specialized listener interface defines at least one method that is used to deliver an object
to the listener.
Methods defined in the listener interface normally take one parameter that is a subclass of
EventObject
Java Event Handling(…cont’d)
Each type of event has it‘s own registration method:
General form:
public void addTypeListener(TypeListener el)
Type:- name of the event
el:- reference to the event listener.
The method that registers a keyboard event listener.
addKeyListener()
The method that registers a mouse motion event listener.
addMouseMotionListener().
Java Event Handling (…cont’d)
Some of the commonly used Events and respective registration method and
setSize(250,250); }
public class Close
addWindowListener(this);
setVisible(true); {
It can be useful if you want to override only some of the methods defined by
that interface.
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.
Adapter classes (…cont’d)
Commonly Used Adapter Classes
Here we implement all the methods provided by the Window listener interface
even though we need only one i.e windowClosing().
So to avoid this we can just create a new class that extends corresponding
adapter class(here it is WindowAdapter class).
The adapter class contains all the methods as defined in the corresponding
interfaces. And we can override the method we need.
//Closing the created frame using window adapter
import [Link].*;
import [Link].*;
public class Close2 extends Frame{
public Close2( ){
setTitle(―AWT Event Program using Adapter class");
setSize(250,250);
addWindowListener(new Myhandler());
setVisible(true);
}
public static void main(String args[]){
Close2 app=new Close2();
}
}
class Myhandler extends WindowAdapter{
public void windowClosing(WindowEvent e){
[Link](0);
}
}
Anonymous Inner Class
First number 32
Second number 12
Result 44
3) AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
5)
AWT doesn't follows MVC Swing follows MVC.
Hierarchy of Java Swing classes
Creating a Frame using Swing
i)JTextField(int cols)
iii)JTextField(String str)
Radio button is a group of related button in which only one can be selected.
JComboBox(String arr[])
import [Link].*;
import [Link].*;
import [Link].*;
public class Test extends JFrame
{
String name[ ] = {"Abebe",―Bekelle","Alex","Hana"}; //list of name.
public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of name.
add(jc); //adding JComboBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
Test ob= new Test();
}
}
6) JProgressBar
The class JProgressBar is a component which visually displays the progress of some
task.
Constructors :
1) JProgressBar() Creates a horizontal progress bar that displays a border but no progress
string.
2) JProgressBar(int orient) Creates a progress bar with the specified orientation, which
can be either SwingConstants VERTICAL or SwingConstants HORIZONTAL.
3) JProgressBar(int min, int max) Creates a horizontal progress bar with the specified
minimum and maximum.
4) JProgressBar(int orient, int min, int max) Creates a progress bar using the specified
orientation, minimum, and maximum.
import [Link].*;
import [Link].*;
import [Link];
import [Link];
Creating a tool tip for any JComponent is easy. Used to display a "Tip" for a Component.
You just use the setToolTipText method to set up a tool tip for the component.
For example, to add tool tips to three buttons, you add only three lines of code:
[Link]("Click this button to disable the middle button.");
[Link]("This middle button does nothing when you click it.");
[Link]("Click this button to enable the middle button.");
import [Link];
import [Link];
public class Tooltipdemo extends JFrame
{
public Tooltipdemo()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Test");
[Link]("Help text for the button");
getContentPane().add(b, "Center");
pack();
}
public static void main(String[] args)
{
new Tooltipdemo().setVisible(true);
}
}
8) Seperator
The JSeparator class provides a horizontal or vertical dividing line or empty space.
It's most commonly used in menus and tool bars.
We can use separators without even knowing that a JSeparator class exists, since menus and
tool bars provide convenience methods that create and add separators customized for their
containers.
Separators are somewhat similar to borders, except that they are the components which are
drawn inside a container, rather than around the edges of a particular component.
Here is a picture of a menu that has three separators, used to divide the menu into four groups
of items:
import [Link].*;
import [Link].*;
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
import [Link].*;
public class TableExample {
JFrame f;
public TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
[Link](30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
[Link](sp);
[Link](300,400);
[Link](true);
}
public static void main(String[] args) {
new TableExample();
}
}
10) JPasswordField
The object of a JPasswordField class is a text component specialized for password entry.
import [Link].*;
public class PasswordFieldExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Password Field Example");
JLabel pa=new JLabel("Password:");
JPasswordField value = new JPasswordField();
[Link](20,100, 80,30);
[Link](100,100,100,30);
[Link](value); [Link](pa);
[Link](300,300);
[Link](null);
[Link](true);
}
}
10) JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box,
confirm dialog box and input dialog box.
These dialog boxes are used to display information or get input from the user.
Constructor Description
JOptionPane() It is used to create a JOptionPane with a test message.
JOptionPane(Object message) It is used to create an instance of JOptionPane to display
a message.
JOptionPane(Object message, int It is used to create an instance of JOptionPane to display
messageType a message with specified message type and default
options.
JOptionPane Example: showMessageDialog()
import [Link].*;
public class OptionPaneExample
{
JFrame f;
public OptionPaneExample()
{
f=new JFrame();
[Link](f,"Hello, Welcome to Java");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
JOptionPane Example: showMessageDialog()
import [Link].*;
public class OptionPaneExample
{
JFrame f;
public OptionPaneExample()
{
f=new JFrame();
[Link](f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Java JOptionPane Example: showInputDialog()
import [Link].*;
public class OptionPaneExample {
JFrame f;
public OptionPaneExample(){
f=new JFrame();
String name=[Link](f,"Enter Name");
}
public static void main(String[] args)
{
new OptionPaneExample();
}
}
JOptionPane Example: showConfirmDialog()
import [Link].*;
public void windowClosing(WindowEvent e)
import [Link].*;
{
public class OptionPaneExample extends WindowAdapter
int a=[Link](f,"Are you sure?");
{
if(a= =JOptionPane.YES_OPTION){
JFrame f;
[Link](JFrame.EXIT_ON_CLOSE);
OptionPaneExample()
}
{
}
f=new JFrame();
public static void main(String[] args)
[Link](this);
{
[Link](300, 300);
new OptionPaneExample();
[Link](null);
}
[Link](JFrame.DO_NOTHING_ON_CLOSE);
}
[Link](true);
}
Dialog boxes and File Dialog
Dialog boxes are pop-up windows on the screen that appear for a small time to take either input or
display output while a main application is running.
Dialog boxes are generally used to draw special attention of the user like displaying warnings.
Dialog box is a top-level window that comes with a border including a title bar.
The dialog box can be made non-resizable and the default layout manager is BorderLayout.
A dialog box works within a main program.
It cannot be created as a standalone application.
It is a child window and must be connected to a main program or to a parent window.
Frame is a parent window as it can work independently.
For example, the Find and Replace Dialog box cannot be obtained without opening MS-Word
document. Likewise, File Deletion Confirmation box cannot appear without deleting a file.
Types of Dialog boxes
Two types of dialog boxes exist
1) Modal
2) Modeless.
Modal dialog box does not allow the user to do any activity without dismissing (closing)
Modeless dialog box permits the user to do any activity without closing it; example
is Find and Replace dialog box of MS Word. Java supports both styles of dialog boxes.
Hierarchy: Object->Component->Container->Window->Dialog
Constructor:
public JDialog(Frame parent) :-Creates an untitled frame window.
public JDialog (Frame parent , String title) :-String argument used as the frame‘s window title.
public JDialog(Frame parent, boolean modal):-
public JDialog(Frame parent,String title, boolean modal) :-
Here parent frame provides the functionality needed to implement an independent
application window.
The argument modal of type boolean specifies whether the dialog box should be modal or
not.
import [Link].*;
import [Link].*;
import [Link].*;
public class SwingDialogExample{
private static JDialog d;
SwingDialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
[Link]( new FlowLayout() );
JButton b = new JButton ("OK");
[Link] ( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
[Link](false);
}
});
[Link]( new JLabel ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[]) {
SwingDialogExample ob=new SwingDialogExample();
} }
≈//≈