0% found this document useful (0 votes)
3 views108 pages

Chapter 3 GUI

Advanced Java Notes About GUI

Uploaded by

kaleabgemechu657
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views108 pages

Chapter 3 GUI

Advanced Java Notes About GUI

Uploaded by

kaleabgemechu657
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ADVANCED PROGRAMMING

CHAPTER ONE
Introduction to Abstract Window Toolkit (AWT)
&
Swings

By: Ketema K.(Asst/Professor)


Objectives
 To design and develop GUI programs using AWT and Swing
component

 To arrange the GUI components using different layout managers

To handle GUI events


A Graphical User Interface (GUI) presents a user-friendly mechanism for
interacting with an application.

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:

1. AWT (Abstract Window Toolkit )

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 a GUI toolkit designed to work across multiple platforms.

Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system.

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.

Therefore, AWT components are platform dependent.


AWT
A graphical user interface is built of graphical elements called components.

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.

Introduced with Java 1.0.

 Must import [Link].* and [Link].*


Java AWT Hierarchy
AWT
Three main type of classes within the package are:
1. Component:- Base class for visual AWT classes, including Container provides
functionality for defining the appearance of the AWT component, the response (if
any) to various events, and the instructions on how to render itself.
It is the ultimate superclass for all nonmenu graphical components and class
CheckboxGroup.
2. Container :- A specialized component that holds other components like buttons,
labels, textfields etc.
3. LayoutManager :- An interface responsible for sizing and positioning components
within a container.
Useful Methods of Component class
Container
 Container is a subclass of Component. (i.e. All containers are themselves, Components)
 Containers contain components such as buttons, textfields, labels etc
 For a component to be placed on the screen, it must be placed within a Container.
 The classes that extends Container class are known as container such as Frame, Dialog
and Panel.
 The Container class defined all the data and methods necessary for managing groups of
Components
add
getComponent
Windows and Frames
 The Window class defines a top-level Window with no Borders or Menu bar.

 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

 Once defined, a Frame is a Container which can contain Components.

Frame aFrame = new Frame(―Hello World‖);

[Link](100,100);

[Link](10,10);

[Link](true);
Creating a Graphical User Interface

GUI programming in Java is based on three concepts:


• Components. A component is an object that the user can see on the screen and—in
most cases—interact with.
• Containers. A container is a component that can hold other components.
• Events. An event is an action triggered by the user, such as a key press or mouse
click.

Designing a graphical user interface involves creating components, putting them into
containers, and arranging for the program to respond to events.
12
Frames

In Java terminology, a frame is a window with a title and a border.

A frame may also have a menu bar.

It can have other components like button, textfield etc.

13
Creating a Frame

We can create a GUI using Frame in two ways:

1) By extending Frame class

2) By creating the instance of Frame class

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):

 Frame f = new Frame("Title goes here");

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.

If desired, the frame‘s location can also be specified.


18
Setting the Location of a Frame
By default, all windows (including frames) are displayed in the upper-left
corner of the screen, which has coordinates (0, 0).

The setLocation method can be used to specify a different location:

[Link](50, 75);

To find the current location of a frame, call getLocation:

Point frameLocation = [Link]();

The coordinates of f‘s upper-left corner will be stored in frameLocation.x and


frameLocation.y.
19
Frame Methods
Many methods used with Frame objects are inherited from Window (Frame‘s
superclass) or from Component (Window‘s superclass).

The setSize method sets the width and height of a frame:

 [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)

The size of a frame can change during the execution of a program.

The getSize method returns a frame‘s current width and height:

 Dimension frameSize = [Link]();

[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 setVisible with true as the argument makes a frame visible:


[Link](true);

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.

An example of adding a button to a frame:

Button b = new Button("Testing");

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

Frame aFrame = new Frame("Button Test");


Cancel
[Link](100,100);
[Link](10,10);
[Link](aPanel);
Buttons
 This class represents a push-button which displays some specified text.
Constructors
1) Button()
Constructs a button with an empty string for its label.
2) Button(String text)
Constructs a new button with specified label.
Panel aPanel = new Panel();
Button okButton = new Button("Ok");
Button cancelButton = new Button("Cancel");
[Link](okButton));
[Link](cancelButton));
Labels
 This class is a Component which displays a single line of text.
 Labels are read-only. That is, the user cannot click on a label to edit the text it displays.
 Text can be aligned within the label.
Constructors Label Ll = new Label("Enter password:");
1) Label() [Link]([Link]);
Constructs an empty label. [Link](aLabel);
2)Label(String text)
Constructs a new label with the specified string of text, left justified.
3)Label(String text, int alignment)
Constructs a new label that presents the specified string of text with the specified alignment.
List
 This class is a Component which displays a list of Strings. The list is scrollable, if necessary.
 Sometimes called Listbox in other languages. Lists can be set up to allow single or multiple
selections.
 The list will return an array indicating which Strings are selected.
Constructors List L1 = new List();
1) List() [Link](―India");
[Link](―UK");
Creates a new scrolling list.
[Link](―USA");
2) List(int rows)
Creates a new scrolling list initialized with the specified number of visible lines.
3List(int rows, boolean multipleMode)
Creates a new scrolling list initialized to display the specified number of rows.
Checkbox
 This class represents a GUI checkbox with a textual label.
 The Checkbox maintains a boolean state indicating whether it is checked or not.
 If a Checkbox is added to a CheckBoxGroup, it will behave like a radio button.
Constructors
1) Checkbox()
Creates a check box with an empty string for its label.
2) Checkbox(String label)
Creates a check box with the specified label.
3)Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified state.
4) Checkbox(String label, boolean state, CheckboxGroup group)
Constructs a Checkbox with the specified label, set to the specified state, and in the specified
check box group.
5)Checkbox(String label, CheckboxGroup group, boolean state)
Creates a check box with the specified label, in the specified check box group, and set to the
specified state.
Checkbox male = new CheckBox(―Male");
Checkbox female = new CheckBox(―Female");
Choice
 This class represents a dropdown list of Strings.
 Similar to a list in terms of functionality, but displayed differently.
 Only one item from the list can be selected at one time and the currently
selected element is displayed.
Choice c = new Choice();
[Link](―India");
[Link](―UK");
[Link](―USA");
TextField
 This class displays a single line of optionally editable text.
 This class inherits several methods from TextComponent.
 This is one of the most commonly used Components in the AWT
TextField emailTextField = new TextField();
abc@[Link]
TextField passwordTextField = new TextField();
[Link](‗*‘); *************
String userEmail = [Link]();
String userpassword = [Link]();
TextArea

 This class displays multiple lines of optionally editable text.


 This class inherits several methods from TextComponent.
 TextArea also provides the methods: appendText(), insertText() and
replaceText()
This is
Text area
// 5 rows, 80 columns
TextArea fullAddressTextArea = new TextArea(5, 80);
String userFullAddress= [Link]();
Layout Managers
 Since the Component class defines the setSize() and setLocation() methods, all Components
can be sized and positioned with those methods.

 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.

 Solution: Layout Managers. Layout managers are assigned to Containers. When a


Component is added to a Container, its Layout Manager is consulted in order to determine
the size and placement of the Component.
Layout Managers (…cont)
 Every container has a default layout manager, but we can explicitly set the
layout manager as well.

 Each layout manager has its own particular rules governing how the
components will be arranged.

 Some layout managers pay attention to a component's preferred size or


alignment, while others do not.

 A layout manager attempts to adjust the layout as components are added and
as containers are resized.

 Therefore, layout managers are used to arrange components in a particular


manner.
Layout Managers (…cont’d)
 There are several different LayoutManagers, each of which sizes and positions its
Components based on an algorithm:

A. FlowLayout

B. BorderLayout

C. GridLayout

D. CardLayout

E. GridBagLayout

 For Windows and Frames, the default LayoutManager is BorderLayout. For


Panels, the default LayoutManager is FlowLayout.
Flow Layout
 The algorithm used by the FlowLayout is to lay out Components like words on a page: Left
to right, top to bottom.
 It fits as many Components into a given row before moving to the next row.
 Rows are created as needed to accommodate all of the components.
 Components are displayed in the order they are added to the container.
 Each row of components is centered horizontally in the window by default, but could also
be aligned left or right.
 Also, the horizontal and vertical gaps between the components can be explicitly set.
 [Link](new FlowLayout());
 FlowLayout class contains three constants you can use to align Components

• [Link]

• [Link]

• [Link]

• If you do not specify alignment, Components are center-aligned in a


FlowLayout Container by default.
Flow Layout Constructors
1)FlowLayout(align, hgap, vgap)
align – alignment used by the manager
hgap – horizontal gaps between components
vgap – vertical gaps between components

2)FlowLayout(align)
align – alignment used by the manager
A default 5-unit horizontal and vertical gap.
import [Link].*;

public class Flowdemo


{
public static void main(String args[])
{
Frame f=new Frame(―FlowLayout‖);
[Link](new FlowLayout([Link],10,10));
Button b1=new Button("One");
Button b2= new Button("Two");
Button b3=new Button("Three");
Button b4= new Button("Four");
Button b5=new Button("Five");
[Link](b1);
[Link](b2);
[Link](b3);
[Link](b4);
[Link](b5);
}
}
Border Layout
 The BorderLayout Manager breaks the Container into 5 regions (North, South, East, West,
and Center).
 When you add a component to a container that uses BorderLayout, the add() method uses
two arguments the component and the region to which the component is added.
Frame aFrame = new Frame();
[Link]("North", new Button("Ok"));
[Link]("South", new Button("Add"));
[Link]("East", new Button("Delete"));
[Link]("West", new Button("Cancel"));
Border Layout (…cont’d)

 The regions of the BorderLayout are defined as follows:

North

West Center East

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) {

Frame f=new Frame("Border layout");


[Link]( new BorderLayout());
[Link]( new Button("ONE"), "North" );
[Link]( new Button("TWO"), "East" );
[Link]( new Button("THREE"), "South" );
[Link]( new Button("FOUR"), "West" );
[Link]( new Button("Five"), "Center" );

[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) {

Frame f=new Frame("Border layout");


[Link]( new GridLayout(3,2));
[Link]( new Button("ONE"));
[Link]( new Button("TWO"));
[Link]( new Button("THREE") );
[Link]( new Button("FOUR"));
[Link]( new Button("Five"));

[Link](400,500);
[Link](true);
}
}
What if I don’t want a LayoutManager?

 LayoutManagers have proved to be difficult to deal with.


 The LayoutManager can be removed from a Container by invoking its
setLayout method with a null parameter.

Panel aPanel = new Panel();


[Link](null);
Frame f=new Frame();
[Link](null);
Menubars
 Menus are a number of pull-down combo boxes (In Java called as Choice) placed at single
place for easy selection by the user.
 To create menus, the [Link] package comes with mainly four classes – MenuBar, Menu,
MenuItem and CheckboxMenuItem.
 All these four classes are not AWT components as they are not subclasses of
[Link] class.
 They are subclasses of [Link].

1) MenuBar: MenuBar holds the menus. MenuBar is added to frame


with setMenuBar() method. Implicitly, the menu bar is added to the north (top) of the
frame. MenuBar cannot be added to other sides like south and west etc.

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.

4) CheckboxMenuItem: It differs from MenuItem in that it appears along with


a checkbox. The selection can be done with checkbox selected.
import [Link].*;
public class SimpleMenuExample extends Frame
{
Menu states, cities;
SimpleMenuExample()
{
MenuBar mb = new MenuBar(); // begin with creating menu bar
setMenuBar(mb); // add menu bar to frame
states = new Menu("Indian States"); // create menus
cities = new Menu("Indian Cities");
[Link](states); // add menus to menu bar
[Link](cities);
[Link](new MenuItem("Himachal Pradesh"));
[Link](new MenuItem("Rajasthan"));
[Link](new MenuItem("West Bengal"));
[Link](); // separates from north Indian states from south Indian
[Link](new MenuItem("Andhra Pradesh"));
[Link](new MenuItem("Tamilnadu"));
[Link](new MenuItem("Karnataka"));
[Link](new MenuItem("Delhi"));
[Link](new MenuItem("Jaipur"));
[Link](new MenuItem("Kolkata"));
[Link](); // separates north Indian cities from south Indian
[Link](new MenuItem("Hyderabad"));
[Link](new MenuItem("Chennai"));
[Link](new MenuItem("Bengaluru"));
setTitle("Simple Menu Program"); // frame creation methods
setSize(300, 300);
setVisible(true);
}
public static void main(String args[]) {
new SimpleMenuExample();
}}
What is Event Handling?
 Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.

This mechanism have the code which is known as event handler that is
executed when an event occurs.

Java Uses the Delegation Event Model to handle the events.

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

c. One or more event listeners.

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

An event is an object that describes a state change in a source.

Activities that cause events can be pressing a button, entering a character


through a keyboard and so on.

An event object embodies information related to a particular type of event.

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.

Each type of event has it‘s own registration method.


Java Event Handling(…cont’d)
Event Listener
 A listener is an object that is notified when an event occurs. It has two major requirements:

It must have been registered with one or more source to receive notifications about specific
types of event.

To do this it must implement the appropriate listener interface.

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

methods to be defined for each listener.


addXXXListener
User Control (interface to be implemented) method in listener
Button/JButton addActionListener() actionPerformed(ActionEvent e)
TextField/JTextField
MenuItem/JMenuItem

CheckBox/JCheckBox addItemListener() itemstateChanged(ItemEvent e)

key on component addKeyListener() keyPressed(KeyEvent e),


keyReleased(KeyEvent e), keyTyped(…)
mouse on component addMouseListener() mouseClicked(MouseEvent e),
mouseEntered(MouseEvent e),
mouseExited(MouseEvent e),
mousePressed(), mouseReleased()

mouse on component addMouseMotionListener() mouseMoved(MouseEvent e),


mouseDragged(MouseEvent e)

Frame/JFrame addWindowListener() windowClosing(WindowEvent e)


windowOpened(WindowEvent e)
windowActivated(WindowEvent e),etc
Example to demonstrate Event Handling in Java setLayout (null);
import [Link].*; setVisible (true);
import [Link].*; }
class EventHandling extends Frame implements ActionListener public void actionPerformed (ActionEvent e)
{ {
TextField textField; [Link] ("Hello World");
public EventHandling ( ) }
{ public static void main (String args[])
textField = new TextField (); {
[Link] (60, 50, 170, 20); new EventHandling ();
Button button = new Button ("Show"); }
[Link] (90, 140, 75, 40); }
[Link] (this);
add (button);
add (textField);
setSize (250, 250);
Example: Attaching Closing Event to the program public void windowOpened(WindowEvent e) {}
import [Link].*; public void windowClosed(WindowEvent e) {}
import [Link].*; public void windowActivated(WindowEvent e) {}
class Close1 extends Frame implements WindowListener public void windowDeactivated(WindowEvent e)
{ {}
public void windowIconified(WindowEvent e) {}
public Close1( ){
setTitle(―AWT Event Program"); public void windowDeiconified(WindowEvent e) {}

setSize(250,250); }
public class Close
addWindowListener(this);
setVisible(true); {

} public static void main(String args[])


{
public void windowClosing (WindowEvent e){
dispose(); // for current frame Close1 c=new Close1();

//[Link](0);// to close the program }


}
//close();
}
Adapter classes
To simplify the creation of event handlers in certain situations.

An adapter class provides empty implementations of all methods in a particular


listener interface.

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

WindowAdapter implements WindowListener

MouseAdapter implements MouseListener

FocusAdapter implements FocusListener

KeyAdapter implements KeyListener

MouseMotion Adapter implements MouseMotionListener

ComponentAdapter implements ComponentListener

ContainerAdapter implements ContainerListener


Adapter classes (…cont’d)
Suppose you want to write code for closing a window.

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

An anonymous inner class is one that is not assigned a name.

Can facilitate the writing of event handlers.


//Closing the created frame using window adapter and anonymous inner class
import [Link].*;
import [Link].*;
Public class Close3 extends Frame{
public Close3(){
setTitle("Event Program using adapter and anonymous inner class");
setSize(250,250);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
[Link](0);
}
}
);
setVisible(true);
}
public static void main(String args[]){
Close3 app=new Close3();
}}
Exercise

First number 32

Second number 12

Result 44

Add Subtract Multiply Division


Swings
Swings in Java
 Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications.
 It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.
What is JFC?
 The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
 Unlike AWT, Java Swing provides platform-independent and lightweight components.
 The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, Jmenu etc.
Swing Features
1. Light Weight - Swing component are independent of native Operating System's API as
Swing API controls are rendered mostly using pure JAVA code instead of underlying operating
system calls.
2. Rich controls - Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, table controls etc.
[Link] Customizable - Swing controls can be customized in very easy way as visual
appearance is independent of internal representation.
[Link] look-and-feel- Swing based GUI Application look and feel can be changed at run
time based on available values.
MVC Architecture
 MVC stands for Model View and Controller. MVC architecture calls for a visual
application to be broken into three separate parts:
 Model represents the state of the application i.e. data.
 View represents the presentation i.e. UI(User Interface).
 Controller acts as an interface between View and Model. Controller intercepts all the
incoming requests. It takes user input on the view.
Difference between AWT and Swing

Java AWT Java Swing


1) AWT components are platform-dependent. Java swing components are platform-
independent.
2) AWT components are heavyweight. Swing components are lightweight.

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

 We can create a GUI Frame in two ways:

1) By extending JFrame class

2) By creating the instance of JFrame class


1. By extending JFrame class
import [Link].*;
public class SwingExample extends JFrame {
public SwingExample(){
setTitle("My first swing program ");
setSize(400,500);
setLocation(50, 75);
setVisible(true);
}
public static void main(String args[]){
SwingExample ob=new SwingExample();
}
77
}
2. By creating instance of JFrame class
import [Link].*;
public class SwingExample {
public SwingExample(){
JFrame f = new JFrame(―My first swing program");
[Link](400, 500);
[Link](50, 75);
[Link](true);
}
public static void main(String[] args)
{
SwingExample ob=new SwingExample();
}
} 78
Swing Components
1) JButton
 JButton class provides functionality of a button. JButton class has three constuctors.
i) JButton(Icon ic)
ii) JButton(String str)
iii) JButton(String str, Icon ic)
 It allows a button to be created using icon, a string or both.
 JButton supports ActionEvent.
 When a button is pressed an ActionEvent is generated.
import [Link].*;
import [Link].*;
public class Testswing extends JFrame
{
public Testswing ()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setSize(400, 400); //setting size of Jframe
setVisible(true);
}
public static void main(String[] args)
{
Testswing ob=new Testswing();
}
}
2) JTextField
 It is used for taking input of single line of text.

 It is most widely used text component.

 It has three constructors,

i)JTextField(int cols)

ii)JTextField(String str, int cols)

iii)JTextField(String str)

 cols represent the number of columns in text field.


import [Link].*;
import [Link].*;
import [Link].*;
public class MyTextField extends JFrame
{
MyTextField()
{
JTextField jtf = new JTextField(20); //creating JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new MyTextField();
}
}
3) JCheckBox

 JCheckBox class is used to create checkboxes in frame.


 Following is constructor for JCheckBox, JCheckBox(String str);
import [Link].*;
import [Link].*;
import [Link].*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox 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();
}}
4) JRadioButton

 Radio button is a group of related button in which only one can be selected.

 JRadioButton class is used to create a radio button in Frames.

Following is the constructor for JRadioButton,JRadioButton(String str)


import [Link].*;
import [Link].*;
import [Link].*;
public class Test extends JFrame {
public Test()
{
JRadioButton r1 = new JRadioButton("A"); //creating JRadioButton.
add(r1); //adding JRadioButton to frame.
JRadioButton r2 = new JRadioButton("B"); //creating JRadioButton.
add(r2); //adding JRadioButton to frame.
JRadioButton r3 = new JRadioButton("C"); //creating JRadioButton.
add(r3); //adding JRadioButton to frame.
JRadioButton r4= new JRadioButton("none");
add(r4);
ButtonGroup bg=new ButtonGroup();
[Link](r1);[Link](r2);[Link](r3);[Link](r4);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args){
Test ob=new Test();
}
}
5) JComboBox

 Combo box is a combination of text fields and drop-down list.


 JComboBox component is used to create a combo box in Swing.

Following is the constructor for JComboBox,

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];

public class ProgressSample


{
public static void main(String args[])
{
JFrame f = new JFrame("JProgressBar Sample");
[Link](JFrame.EXIT_ON_CLOSE);
Container content = [Link]();
JProgressBar progressBar = new JProgressBar();
[Link](25);
[Link](true);
Border border = [Link]("Reading...");
[Link](border);
[Link](progressBar, [Link]);
[Link](300, 100);
[Link](true);
}
}
7) ToolTips

 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].*;

public class SeparatorDemo


{
public static void main(String args[])
{
JFrame f = new JFrame("JSeparator Sample");
[Link](JFrame.EXIT_ON_CLOSE);
Container content = [Link]();
[Link](new GridLayout(0, 1));
JLabel above = new JLabel("Above Separator");
[Link](above);
JSeparator separator = new JSeparator();
[Link](separator);
JLabel below = new JLabel("Below Separator");
[Link](below);
[Link](300, 100);
[Link](true);
}
}
9) JTable

 The JTable class is used to display data in tabular form.

 It is composed of rows and columns.

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.

 The JOptionPane class inherits JComponent class.

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)

it; example is File Deletion Confirmation dialog box .

 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();
} }
≈//≈

You might also like