Unit V
GUI Programming:
Java AWT
AWT stands for Abstract Window Toolkit. It is a platform dependent
API for creating Graphical User Interface (GUI) for java programs.
Java AWT components are platform-dependent i.e. components are
displayed according to the view of the operating system. For example an
AWT GUI having a button would have a different look and feel across
platforms like windows, Mac OS & Unix,
AWT is heavyweight i.e. its components are using the resources of
OS.AWT components are considered heavy weight because they are
being generated by the underlying operating system (OS). For example
if you are instantiating a text box in AWT that means you are actually
asking the OS to create a text box for you.
AWT is rarely used nowadays because of its platform dependent and
heavy-weight nature.
The java.awt package provides classes for AWT api such
as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
Components and containers
All the elements like buttons, text fields, scrollbars etc are known as
components. In AWT we have classes for each component as shown in
the above diagram.
To have everything placed on a screen to a particular position, we have
to add them to a container. A container is like a screen wherein we are
placing components like buttons, text fields, checkbox etc.
In short a container contains and controls the layout of components. A
container itself is a component (shown in the above hierarchy diagram)
thus we can add a container inside the container.
Types of containers:
As explained above, a container is a place wherein we add components
like text field, button, checkbox etc. There are four types of containers
available in AWT: Window, Frame, Dialog and Panel. As shown in the
hierarchy diagram above, Frame and Dialog are subclasses of Window
class.
Window: The window is the container that has no borders and menu
bars.
Dialog: Dialog class has a border and a title.
Panel: Panel does not contain title bar, menu bar or border. It is a
generic container for holding components.
Frame: A frame has title, border and menu bars. It can contain several
components like buttons, text fields, scrollbars etc. This is the most
widely used container while developing an application in AWT.
INTRODUCTION TO SWING:
Unlike AWT, Java Swing provides platform-independent and
lightweight components.
The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Swing is a preferred API for window based applications because of its
platform independence and light-weight nature.
Swing is built upon AWT API however it provides a look and feel
unrelated to the underlying platform.
It has more powerful and flexible components than AWT. In addition to
familiar components such as buttons, check boxes and labels, Swing
provides several advanced components such as tabbed panels, scroll
panes, trees, tables, and lists.
Limitations of AWT:
The AWT defines a basic set of controls, windows, and dialog
boxes that support a usable, but limited graphical interface. One reason
for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or
peers. This means that the look and feel of a component is defined by
the platform, not by java. Because the AWT components use native
code resources, they are referred to as heavy weight.
The use of native peers led to several problems.
First, because of variations between operating systems, a component
might look, or even act, differently on different platforms. This
variability threatened Java's philosophy: write once, run anywhere.
Second, the look and feel of each component was fixed and could not
be changed. Third, the use of heavyweight components caused some
frustrating restrictions. Due to these limitations Swing came and was
integrated into java. Swing is built on the AWT. Two key Swing
features are: Swing components are lightweight, Swing supports a
pluggable look and feel.
Differences between AWT and Swing
AWT Swing
AWT components are called Swings are called light weight
Heavyweight components. components because swing
components sit on the top of
AWT components and do the
work.
AWT components are platform Swing components are made in
dependent. purely java and they are platform
independent.
AWT components require the Swi compon requi javax.s
java.awt package. ng ents re wing
pack
age.
AWT is a thin layer of code on top Swing is much larger. Swing
of the OS. also has much richer
functionality.
AWT stands for Abstract windows Swing is also called as JFC’s
toolkit. (Java Foundation classes).
This feature is not supported in We can have a different look and
AWT. feel in Swing.
Using AWT, you have to Swing has them built in.
implement a lot of things
yourself.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that
are given below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int sets the size of the component.
height)
public void sets the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean b) sets the visibility of the component. It is
by default false.
Swing components:
Java JButton
The JButton class is used to create a labeled button that has
platform independent implementation. The application results in
some action when the button is pushed. It inherits the
AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
Commonly used Methods of AbstractButton class:
Methods Description
void setText(String s) It is used to set specific text on
button
String getText() It is used to return the text of the
button.
void setEnabled(boolean b) It is used to enable or disable the
button.
void setIcon(Icon b) It is used to set the specified Icon
on the button.
Icon getIcon() It is used to get the Icon of the
button.
void setMnemonic(int a) It is used to set the mnemonic on
the button.
void It is used to add the action
addActionListener(ActionListener a) listener to this object.
Java JButton Example
import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Java JTextField
The object of a JTextField class is a text component that allows the
editing of a single line text. It inherits the JTextComponent class.
JTextField class declaration
Let's see the declaration for javax.swing.JTextField class.
public class JTextField extends JTextComponent implements Swing
Constants
JTextField t1=new JTextField("Welcome to Javatpoint.");
Commonly used Constructors:
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the
specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
JTextField(int columns) Creates a new empty TextField with the
specified number of columns.
Commonly used Methods:
Methods Description
void addActionListener(ActionListener It is used to add the specified
l) action listener to receive action
events from this textfield.
Action getAction() It returns the currently set Action
for this ActionEvent source, or
null if no Action is set.
void setFont(Font f) It is used to set the current font.
void It is used to remove the specified
removeActionListener(ActionListener l) action listener so that it no longer
receives action events from this
textfield.
Java JTextField Example
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Java JLabel
The object of the JLabel class is a component for placing text in a
container. It is used to display a single line of read only text. The text
can be changed by an application but a user cannot edit it directly.
It inherits the JComponent class.
JLabel class declaration
Let's see the declaration for javax.swing.JLabel class.
public class JLabel extends JComponent implements SwingConstant
s, Accessible
Commonly used Constructors:
Constructor Description
JLabel() Creates a JLabel instance with no image
and with an empty string for the title.
JLabel(String s) Creates a JLabel instance with the
specified text.
JLabel(Icon i) Creates a JLabel instance with the
specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the
horizontalAlignment) specified text, image, and horizontal
alignment.
Commonly used Methods:
Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this
component will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents
alignment) along the X axis.
Icon getIcon() It returns the graphic image that the label
displays.
int getHorizontalAlignment() It returns the alignment of the label's
contents along the X axis.
Java JLabel Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Java JTextArea
The object of a JTextArea class is a multi line region that displays
text. It allows the editing of multiple line text. It inherits
JTextComponent class
JTextArea class declaration
Let's see the declaration for javax.swing.JTextArea class.
1. public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text
initially.
JTextArea(int row, int Creates a text area with the specified number of
column) rows and columns that displays no text initially.
JTextArea(String s, int Creates a text area with the specified number of
row, int column) rows and columns that displays specific text.
Commonly used Methods:
Methods Description
void setRows(int rows) It is used to set a specified number of rows.
void setColumns(int cols) It is used to set a specified number of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int It is used to insert the specified text on the
position) specified position.
void append(String s) It is used to append the given text to the end of
the document.
Java JTextArea Example
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample()
{
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Output:
Layout Manager:
BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in a
particular manner. The Java LayoutManagers facilitates us to control
the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes
of layout managers. There are the following classes that represent
the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five
regions: north, south, east, west, and center. Each region (area) may
contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps
between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with
the given horizontal and vertical gaps between the
components.
Example of BorderLayout class: Using BorderLayout()
constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{ f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled
as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled a
s SOUTH JButton b3 = new JButton("EAST");; // the button will be
labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled a
s WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled
as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North
Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South
Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Dire
ction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West D
irection
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Cent
er
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
OUTPUT:
Java GridLayout
The Java GridLayout class is used to arrange the components in a
rectangular grid. One component is displayed in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per
component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with
the given rows and columns but no gaps between the
components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a
grid layout with the given rows and columns along with given
horizontal and vertical gaps.
Example of GridLayout class: Using GridLayout() Constructor
The GridLayout() constructor creates only one row. The following
example shows the usage of the parameterless constructor.
FileName: GridLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample
{
JFrame frameObj;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
// since, we are using the parameterless constructor, therefore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
// setting the grid layout using the parameterless constructor
frameObj.setLayout(new GridLayout(3,3));
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a
line, one after another (in a flow). It is the default layout of the
applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Field
Following are the fields for java.awt.BorderLayout class:
static int CENTER -- This value indicates that each row of components should
be centered.
static int LEADING -- This value indicates that each row of components should
be justified to the leading edge of the container's orientation, for example, to the
left in left-to-right orientations.
static int LEFT -- This value indicates that each row of components should be
left-justified.
static int RIGHT -- This value indicates that each row of components should be
right-justified.
static int TRAILING -- This value indicates that each row of components should
be justified to the trailing edge of the container's orientation, for example, to the
right in left-to-right orientations.
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment
and a default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given
alignment and a default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout
with the given alignment and the given horizontal and vertical
gap.
Example of FlowLayout class: Using FlowLayout()
constructor
FileName: FlowLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample
{
JFrame frameObj;
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();
// creating the buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameOb
j.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameO
bj.add(b8);
frameObj.add(b9); frameObj.add(b10);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:
MVC architecture:
In general, a visual component is a composite of three distinct
aspects:
• The way that the component looks when rendered on the screen
• The way that the component reacts to the user
• The state information associated with the component
Over the years, one component architecture has proven itself to
be exceptionally effective: Model-View-Controller, or MVC for short.
The MVC architecture is successful because each piece of the
design corresponds to an aspect of a component.
In MVC terminology,
The model corresponds to the state information associated with
the component. For example, in the case of a check box, the model
contains a field that indicates if the box is checked or unchecked.
The view determines how the component is displayed on the
screen, including any aspects of the view that are affected by the
current state of the model.
The controller determines how the component reacts to the user.
For example, when the user clicks a checkbox, the controller reacts by
changing the model to reflect the user’s choice (checked or unchecked).
This then results in the view being updated. By separating a component
into a model, a view, and a controller, the specific implementation of
each can be changed without affecting the other two. For instance,
different view implementations can render the same component in
different ways without affecting the model or the controller.
MVC Architecture
Model designs based on MVC architecture follow the MVC design
pattern and they separate the application logic from the user interface
when designing software. As the name implies MVC pattern has three
layers, which are:
Model – Represents the business layer of the application
View – Defines the presentation of the application
Controller – Manages the flow of the application
This separation results in user requests being processed as
follows:
1. The browser on the client sends a request for a page to the controller
present on the server
2. The controller performs the action of invoking the model, thereby,
retrieving the data it needs in response to the request
3. The controller then gives the retrieved data to the view
4. The view is rendered and sent back to the client for the browser to
display
Advantages of MVC Architecture in Java
MVC architecture offers a lot of advantages for a programmer when
developing applications, which include:
● Multiple developers can work with the three layers (Model, View, and
Controller) simultaneously
● Offers improved scalability, that supplements the ability of the
application to grow
● As components have a low dependency on each other, they are easy
to maintain
● A model can be reused by multiple views which provides reusability
of code
● Adoption of MVC makes an application more expressive and easy to
understand
● Extending and testing of the application becomes easy
Components of Swing:
JButton:
The JButton class is used to create a labeled button that has platform
independent implementation. The application results in some action
when the button is pushed.
Syntax:
JButton b=new JButton(“Text");
(Or)
JButton b1,b2;
b1=new JButton(“Text”);
b.setBounds(50,100,80,30);
JLabel:
The JLabel class is a component for placing text in a container. It is used
to display a single line of read only text. The text can be changed by an
application but a user cannot edit it directly.
Syntax:
JLabel l1=new JLabel(“Text”);
(or)
JLabel l1,l2;
l1=new JLabel(“Text”);
JTextField:
The JTextField class is a text component that allows the editing of a
single line text.
Syntax:
JTextField t1=new JTextField(“Text”);
(or)
JTextField t1,t2;
t1=new JTextField(“Text”);
JTextArea :
The JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text.
Syntax:
JTextArea t1=new JTextArea(“Text”);
(or)
JTextArea t1,t2;
t1=new JTextArea(“Text”);
JCheckBox :
The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a Checkbox changes its state
from "on" to "off" or from "off" to "on".
Syntax:
JCheckBox c1=new JCheckBox(“Text”);
(or)
JCheckBox c1,c2;
c1=new JCheckBox(“Text”);
Example program:
// importing AWT class
import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
f.add(checkbox2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main (String args[])
{
new CheckboxExample1();
}
}
JList
The object of the JList class represents a list of text items. The list of text
items can be set up so that the user can choose one or more items from
a list of items.
Syntax:
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList list = new JList<>(l1);
ListExample1.java
// importing awt class
import java.awt.*;
public class ListExample1
{
// class constructor
ListExample1() {
// creating the frame
Frame f = new Frame();
// creating the list of 5 rows
List l1 = new List(5);
// setting the position of list component
l1.setBounds(100, 100, 75, 75);
// adding list items into the list
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
// adding the list to frame
f.add(l1);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new ListExample1();
}
}
JPasswordField:
The JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text.
Syntax:
JPasswordField pwd = new JPasswordField();
pwd.setBounds(100,50,80,30);
Java JPasswordField Example
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JRadioButton
The JRadioButton class is used to create a radio button. It is used
to choose one option from multiple options. It is widely used in exam
systems or quizzes.
• It should be added in ButtonGroup to select one radio button only.
Syntax:
ButtonGroup bg=new ButtonGroup();
JRadioButton r1=new JRadioButton("Male");
JRadioButton r2=new JRadioButton("Female");
bg.add(r1);bg.add(r2);
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
JComboBox:
The JComboBox class is used to show a popup menu of items.
Item selected by the user are shown on the top of a menu (like Choice
class in AWT)
Syntax:
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
JTable:
The JTable class is used to display data in tabular form. It is
composed of rows and columns.
Syntax:
String data[][]= { {“521",“Madhu",“43400"}, {“512",“Hari",“54500"},
{“509",“Ganesh","70000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JPanel:
The JPanel is the simplest container class. It provides space in
which an application can attach any other component.
Syntax:
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
panel.add(b1);
JDialog:
The JDialog control represents a top level window with a border
and a title used to take some form of input from the user.
• Unlike JFrame, it doesn't have maximize and minimize buttons.
Syntax:
JFrame f= new JFrame();
JDialog d=new JDialog(f , "Dialog", true);
JButton b = new JButton ("OK");
d.add(b);
Example: An example for JButton Component in swing.
JButtonExample.java
import javax.swing.*;
public class JButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Execution:
D:/>javac JButtonExample.java
D:/>java JButtonExample
Example: An example for a Login page which includes
JLabel,JTextField,JPasswordField, JCheckBox and JButton Components.
LoginExample.java
import javax.swing.*;
class LoginExample extends JFrame
{
public static void main(String args[])
{
JLabel l1,l2;
JTextField t1;
JPasswordField p1;
JCheckBox cb;
JButton b;
JFrame f=new JFrame(“Login Page”);
l1=new JLabel("User Name :");
l1.setBounds(50,60,100,30);
t1=new JTextField("");
t1.setBounds(150,60, 200,30);
l2=new JLabel("Password :");
l2.setBounds(50,120,100,30);
p1=new JPasswordField("");
p1.setBounds(150,120, 200,30);
cb=new JCheckBox("Save Password");
cb.setBounds(50,150,200,30);
b=new JButton("Login");
b.setBounds(150,180,100,30);
f.add(l1);
f.add(l2);
f.add(t1);
f.add(p1);
f.add(cb);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Execution:
D:/>javac LoginExample.java
D:/>java LoginExample
Example: An example for JPanel Class component of swing
JPanelExample.java
import java.awt.*;
import javax.swing.*;
public class JPanelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1);
panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Execution:
D:/> javac JPanelExample.java
D:/> java JPanelExample
Example: An example for JRadioButton Class component of swing
JRadioButtonExample.java
import javax.swing.*;
public class JRadioButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();
JRadioButton r1=new JRadioButton(" Male");
JRadioButton r2=new JRadioButton(" Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.setTitle(“RadioButtonExample”);
}
}
Output:
Javac JRadioButtonExample.java
Java JRadioButtonExample
Example: An example for JList Class component of swing
JListExample.java
import javax.swing.*;
public class JListExample
{
public static void main(String args[])
{
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setTitle(“JList Example”);
}
}
Output:
Javac JListExample.java
Java JListExample
Example: An example for JTable Class component of swing
JTableExample.java
import javax.swing.*;
public class JTableExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();
String data[][]={{"521","Madhu","43400"},
{"512","Hari","54500"},
{"509","Ganesh","70000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
f.setTitle("JTable Example");
}
}
Output:
Javac JTableExample.java
Java JTableExample
Example: An example for JOptionPane Class component of swing
JOptionPaneExample.java
import javax.swing.*;
public class JOptionPaneExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Swing.");
}
}
Output:
Javac JOptionPaneExample.java
Java JOptionPaneExample
Example: An example for JTextArea Class component of swing
JTextAreaExample.java
import javax.swing.*;
class JTextAreaExample
{
public static void main(String args[])
{
JFrame f= new JFrame("JTextArea Example");
JTextArea area=new JTextArea("Welcome");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Javac JTextAreaExample.java
Java JTextAreaExample
Example: An example for JProgressBar Class component of swing
JProgressBarExample.java
import javax.swing.*;
public class JProgressBarExample extends JFrame
{
JProgressBar jb;
int i=0,num=0;
JProgressBarExample()
{
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
setTitle(“JProgressBar”);
}
public void iterate()
{
while(i<=2000)
{
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);
}
catch(Exception e)
{
}
}
}
public static void main(String[] args)
{
JProgressBarExample m=new JProgressBarExample();
m.setVisible(true);
m.iterate();
}
}
Output:
Javac JProgressBarExample.java
Java JProgressBarExample
Applet
An applet is a Java program that runs in a Web browser. (or)
Applet is a special type of program that is embedded in the webpage to
generate dynamic content. It runs inside the browser and works at the
client side.
Any applet in Java is a class that extends the java.applet.Applet class.
Advantage of Applet:
There are many advantages of applets. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many platforms,
including Linux, Windows, Mac Os etc.
Hierarchy of Applet :
As displayed in the diagram, the Applet class extends Panel. Panel class
extends Container, which is the subclass of Component. Where Object
class is base class for all the classes in java.
JApplet class is an extension of Applet class.
Life Cycle of Applet:
There are 5 lifecycle methods of Applet, Those are
public void init(): is used to initialize the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
public void paint(Graphics g): is invoked immediately after the start()
method, and this method helps to create Applet’s GUI such as a colored
background, drawing and writing.
public void stop(): is used to stop the Applet. It is invoked when Applet
is stopped or the browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only
once.
The method execution sequence when an applet is executed is:
● init()
● start()
● paint()
The method execution sequence when an applet is closed is:
● stop()
● destroy()
Simple example of Applet:
To execute an Applet, First Create an applet and compile it just like a
simple java program.
First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g){
g.drawString(“Welcome to Applet",50,150);
}
}
Compile:
D:\> javac First.java
After successful compilation, we get the First.class file.
After that create an html file and place the applet code in the html file.
First.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Execute:
D:\> appletviewer First.html
Displaying Graphics in Applet:
java.awt.Graphics class provides many methods for graphics
programming.
The Commonly used methods of Graphics class:
• drawString(String str, int x, int y): is used to draw the specified string.
• drawRect(int x, int y, int width, int height): draws a rectangle with
the specified
width and height.
• fillRect(int x, int y, int width, int height): is used to fill rectangle with
the default
color and specified width and height.
• drawOval(int x, int y, int width, int height): is used to draw oval with
the
specified width and height.
• fillOval(int x, int y, int width, int height): is used to fill oval with the
default color
and specified width and height.
• drawLine(int x1, int y1, int x2, int y2): is used to draw a line between
the points(x1, y1) and (x2, y2).
• setColor(Color c): is used to set the graphics current color to the
specified color.
• setFont(Font font): is used to set the graphics current font to the
specified font.
Example: GraphicsDemo.java
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
}
}
GraphicsDemo.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
Execution:
D:\> javac GraphicsDemo.java
D:\> appletviewer GraphicsDemo.html
Components of Applet:
The components of AWT are the components of Applet,i.e we can
use AWT components (Button,TextField,Checkbox, TextArea,Choice &
etc.…) in applet.
As we perform event handling in AWT or Swing, we can perform it
in applet also.
Let's see a simple example of components and event handling in
an applet that prints a message by clicking on the button.
Example: AppletComponents.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AppletComponents extends Applet implements
ActionListener
{
Button b;
TextField tf;
public void init()
{
tf=new TextField();
tf.setBounds(80,40,150,20);
b=new Button("Click");
b.setBounds(80,120,80,30);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
}
AppletComponents.html
<html>
<body>
<applet code="AppletComponents.class" width="300" height="300">
</applet>
</body>
</html>
Execution:
D:\>javac AppletComponents.java
D:\>appletviewer AppletComponents.html
JApplet Class:
As we prefer Swing to AWT. Now we can use JApplet that can have
all the controls of swing. The JApplet class extends the Applet class.
The components of swing are the components of JApplet,i.e we
can use swing components (JButton,JTextField,JCheckBox,
JTextArea,JList & etc.…) in JApplet.
Example: JAppletComponents.java
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class JAppletComponents extends JApplet implements
ActionListener
{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(50,40,150,20);
b=new JButton("Click");
b.setBounds(50,100,70,30);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
JAppletComponents.html
<html>
<body>
<applet code="JAppletComponents.class" width="300" height="300">
</applet>
</body>
</html>
Execution:
D:\>javac JAppletComponents.java
D:\>appletviewer JAppletComponents.html
Event Handling:
Event: Changing the state of an object (component) is known as an
event. For example, clicking on a button, dragging a mouse etc.
Event describes the change in state of the component. Events are
generated as a result of user interaction with the graphical user
interface components. For example, clicking on a button, moving the
mouse, entering a character through the keyboard and selecting an
item from the list.
Def: Event Handling is the mechanism that controls the event and
decides what should happen if an event occurs.
This mechanism has the code which is known as an event handler
that is executed when an event occurs.
The java.awt.event package provides many event classes and
Listener interfaces for event handling.
Steps to perform Event Handling:
Following steps are required to perform event handling:
– Register the component with the Listener.
By using addActionListener(ActionListener a)
Example:
Button b=new Button(“Submit”);
b.setBounds(100,50,80,30);
b.addActionListener(this);
– Provide or put event handling code.
By using the actionPerformed(ActionEvent e) method of ActionListener
Interface,we can perform actions that the user wants.
Example:
Public void actionPerformed(ActionEvent e)
{
tf.setText(“welcome”);
}
Simple Example:
import java.awt.*;
import java.awt.event.*;
class EventExample extends Frame implements ActionListener{
TextField tf;
EventExample(){
tf=new TextField(); //create components
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);//register listener passing current instance
add(b);
add(tf); //add components and set size, layout and visibility
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new EventExample();
}
}
Output: javac EventExample.java
java EventExample