CH 1
CH 1
University
Department of
Software engineering
Advanced
programming(SEng6132)
Chapter 1
AWT and Swing
Topic we discussed
1.1. Concepts of AWT and Swing
1.2. Event Handling
1.1. Concepts of AWT
and Swing
We are going to discuss AWT and Swing.
Java GUI
A graphical user interface (GUI) presents a user-
friendly mechanism for interacting with an application.
It gives an application a distinctive “look” and “feel.”
Providing different applications with consistent,
intuitive user interface components allows users to be
somewhat familiar with an application, so that they can
learn it more quickly and use it more productively. GUIs
are built from GUI components. These are sometimes
called controls or widgets.
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.
Cont...
Java has two GUI packages,
1. Abstract Windows Toolkit (AWT) - first (original)
2. Swing - newer
AWT
When java was introduced, the GUI classes were
bundled in a library known as Abstract Windows
Toolkit (AWT).
It is Java’s original set of classes for building GUIs. It
uses peer components of the OS;
It is heavyweight and uses the native operating
system's window routines so the visual effect is
dependent on the run-time system platform.
Swing
AWT is a collection of GUI components (widgets) and
other related services required for GUI programming in
Java.
It designed to solve AWT’s problems (since Java 2). It is
99% java;
It is lightweight components as drawing of components
is done in java.
Swing GUI components allow you to specify a uniform
look-and-feel for your application across all platforms. It
also lays out consistently on all Oss. It has much bigger
set of built-in components and uses AWT event
handling.
Cont...
Swing is built “on top of” AWT, so you need to import
AWT and use a few things from it.
Swing is more flexible and better looking. Swing and
AWT are incompatible. Thus, you can use either, but
you can’t mix them.
Basic components/controls are practically the same in
both. For example:
AWT: Button b = new Button ("OK");
Swing: JButton b = new JButton("OK");
Swing vs AWT
AWT Swing
First Java GUI library A newer, more robust, and
simple graphical user flexible library .
interfaces lightweight components
heavyweight components. complex GUI projects.
platform dependent platform independent
execute slow Execute fast
does not support MVC Support MVC pattern
pattern
Does not require more
require more memory
memory space
space
Java GUI API
Java GUI APIs are categorized into three groups.
These are
1. Container class,
2. Component classes and
3. Helper class.
GUI Container classes
A GUI is built by putting components/controls into
containers. Thus, container is used to group
components.
Frames, Panels and applets are examples of
containers. Important Container classes are JFrame,
JApplet, JDialog and JPanel.
Frame
A resizable, movable window with title bar and close
button. Usually it contains JPanels. It is a container
that holds other Swing user-interface components in
Java GUI application.
Jpanel
JPanel is a region internal to a JFrame or another
JPanel. It is used for grouping components together.
JPanel is optionally bounded by a visible border . It
lives inside some enclosing Container. Panels can be
nested, that is, you can place panels inside a
container that includes a panel. In fact, every frame
has at least one pane, the default “Content Pane”.
GUI Component classes
GUI Components or Controls (also known as
"widgets") are the basic user interface elements the
user interacts with. These include labels, buttons and
text fields.
The visual arrangement of the components depends
on the container's layout (which are part of helper
classes).
The following are list of controls in the javax.swing
package
Cont...
Input Components
Buttons ( JButton, JRadioButtons, JCheckBox)
Text (JTextField, JTextArea)
Menus (JMenuBar, JMenu, JMenuItem)
Sliders (JJSlider
JComboBox (uneditable) (JComboBox)
List (Jlist )
Cont...
Information Display Components
JLabel
Progress bars (JProgressBar)
Tool tips (using JComponent's setToolTipText(s) method)
Choosers
File chooser (JFileChooser)
Color chooser (JColorChooser)
Cont...
More complex displays
Tables (JTable)
Trees (JTree)
GUI helper classes
Helper classes are used to describe the properties of
GUI components.
It encompasses the classes for graphics context, colors,
fonts and dimension.
Graphics: It is an abstract class that provides a graphical
context for drawings strings, lines, and simple shapes.
Cont....
Color: It deals with the colors of GUI components.
For example, we can specify background colors in
components like JFrame and JPanel while we can
specify colors of lines, shapes and etc.
Font: It specifies fonts for the text and drawings on
GUI components. Font is available on the java.awt
package.
Develop GUI
Application
JFrame
It is like the main window of the GUI application using
swing. Created by 2 different ways.
By extending JFrame class and by Instantiating The JFrame
Class.
Frame is a window that is not contained inside another
window.
Applications with a GUI typically use at least one frame.
It used to create windows. It has two constructor namely
JFrame() and JFrame(String title).
To create window with title are
JFrame frame = new JFrame(“My First JFrame”);
Cont…
Some method of JFrame are the following:-
setSize(width, height) //specify the width and the height frame.
setLocation(x, y) //specify the upper and left corner of location
of frame. Short cut(setBounds(x, y, w, h)
add() to add button, input and other to frame.
setVisible(visible, Boolean) // say true to display the frame.
setDefaultCloseOperation(mode: int) // specify the opration
when the frame is closed. To specify there are 3
choice(JFrame.EXIT_ON_CLOSE,
JFrame.HIDE_ON_CLOSE,
JFrame.DO_NOTHING_ON_CLOSE).
Sample of code
package helloworld;
import javax.swing.*;
/** * @author Administrator
*/
public class Helloworld {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
////create a JFrame object
JFrame f = new JFrame("Advanced programming JFrame example");
f.setBounds(40, 80, 200, 200); //set the size(width, height) and the location(x, y)
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true); //make the frame visible
}
}
JButton
The JButton class is used to create a labeled button that has platform independent
implementation.
It has the following constructor(JButton(), JButton(Icon icon), JButton(String text) and
JButton(String text, Icon icon))
It has the following method(setText(String text) , getText(),etc)
setEnabled(boolean b) )
To create JButton
JButton btn = new Jbutton()
button.setText(“Click Here”); or
JButton button= new JButton(“Click Here");
Sample of code
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);
}
}
JLabel
A label is a display area for a short text(a non-editable), an image, or both.
A JLabel component can be created using one of the following constructors(JLabel(),
JLabel(String text), JLabel(Icon icon) etc)
JLabel component has various methods including the following:(getText(),
setText(String), getIcon(), setIcon(Icon icon))
To create JLabel with text
JLabel label = new Jlabel(“First name”)
Sample of code
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,;
l1=new JLabel("First name:");
l1.setBounds(50,50, 100,30);
f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField
A text field is a box that contains a line of text. The user can type text into the box and
the program can get it and then use it as data. The program can write the results of a
calculation to a text field. Text fields are useful in that they enable the user to enter in
variable data (such as a name or a description).
JTextField is swing class for an editable text display.
Its component are (JTextField(), JTextField(int columns), JTextField(String text),
JTextField(String text, int columns))
And have a method in JTextField (getText(), setText(String text), setEditable(boolean
editable) etc)
To create JTextField without text
JTextField Fname= new JTextField();
Sample of code
import javax.swing.*;
// Main class TextFieldExample
class TextFieldExample
{
public static void main(String args[])
{
// Creating a JFrame object with title "TextField Example."
JFrame f= new JFrame("TextField Example");
// Creating two JTextField objects
JTextField t1;
// Initializing the first JTextField with default text "Welcome to Javatpoint."
t1 = new JTextField("Welcome to Javatpoint.");
// Setting the position and size of the first JTextField
t1.setBounds(50,100, 200,30);
// Initializing the second JTextField with default text "AWT Tutorial"
// Setting the position and size of the second JTextField
// Adding JTextFields to the JFrame
f.add(t1); // Setting the size of the JFrame
f.setSize(400,400);
// Setting layout to null to use absolute positioning
f.setLayout(null);
// Making the JFrame visible
f.setVisible(true);
}
}
JPasswordField
Allows the editing of a single line of text where the view indicates something
was typed, but does not show the original characters.
The object of a JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text.
It has the following constructer(JPasswordField(), JPasswordField(int columns),
JPasswordField(String text), JPasswordField(String text, int columns))
JPasswordField with text can be created by
JPasswordField pass = new JPasswordField(“Enter password);
Sample of code
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);
}
}
JTextArea
If you want to let the user enter multiple lines of text, you cannot use text fields
unless you create several of them. The solution is to use JTextArea class, which
enables the user to enter multiple lines of text.
Its constructor includes(JTextArea(int rows, int columns), JTextArea(String s, int
rows, int columns) )
To create JTextArea with row and column
JTextArea ta = new JTextArea(3, 5);
Sample of code
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();
}
}
JCheckBox
It is a widget that has two states. On and Off. It is a box with a label. If the
checkbox is checked, it is represented by a tick in a box
JCheckBox component can be created using one of the following
constructors(JCheckBox(), JCheckBox(Icon icon), JCheckBox(Icon icon,
boolean selected), JCheckBox(String text) etc)
To create JCheckBox with text and Boolean selected
JCheckBox check = new JCheckBox(“Blue”, true);
Sample of code
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Java 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 quiz.
It should be added in ButtonGroup to select one radio button
only.
To create JRadioButton the following constructor are necessary
(JRadioButton(), JRadioButton(String s), JRadioButton(String s,
boolean selected))
Method that used in JRadioButton are (setText(String s),
getText(), setEnabled(boolean b) etc).
Sample of code
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();
}
}
Java JTable
The JTable class is used to display data in tabular form. It is
composed of rows and columns.
The following constructor are used to create
JTable(JTable() - Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) - Creates a table with
the specified data
Example:- JTable table = new Jtable(data, column);
Sample of code
import javax.swing.*;
public class TableExample {
JFrame f;
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);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Java JComboBox
The object of Choice class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu.
The constructor are
(JComboBox() - Creates a JComboBox with a default data model.
JComboBox(Object[] items) etc) - Creates a JComboBox that contains
the elements in the specified array
Some method are (addItem(Object anObject), removeItem(Object
anObject), removeAllItems() etc)
It look like
Sample of code
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
JFileChooser
FileChooser is a class that is present in the java Swing package.
JFileChooser contains many elements that assist in building a graphical user
Interface in java.
JFileChooser is a simple and successful method for inciting the client to pick
a file or a directory.
The Constructors that Present in Java JFileChooser Class are
(JFileChooser(), JFileChooser(File currentDirectory) and other)
Sample of code
// program to demonstrate the JFileChooser(File currentDirectory) cons
tructor
// importing the required packages
import java.io.*;
importjavax.swing.*;
importjava.awt.event.*;
importjavax.swing.filechooser.*;
classHelloWorld
{
public static void main(String[] args) {
// creating object to the JFileChooser class
JFileChooser
jf = new JFileChooser("c:"); // parameterised constructor JFileChooser(
File currentDirectory) is called.
jf.showSaveDialog(null); // opening the saved dialogue
}
}
Java JOptionPane
In Java, JOptionPane is a part of the Java Swing library. It helps us to
create dialog boxes such as message dialogs, conformation dialogs, input
dialogs, and options dialogs In this article, we are going to explore some
constructors, methods, and some examples of JOptionPane.
It has the following constructor
JOptionPane() - This is the default constructor for JOptionPane.It is
used to create a JOptionPane with no options and message.
JOptionPane(Object message) - It creates a message dialog with a
specified message.
JOptionPane(Object message, int messageType) - It creates a message
dialog with a specified message and its Type.
Cont…
It have different method
createDialog(String title) - It helps us to create JDialog with a specified
title but without any parent.
showMessageDialog(Component parentComponent, Object
message) - This method displays a message dialog with the specified
message.
showInputDialog(Component parentComponent, Object message) -
This method displays an input dialog with the specified message.
setOptionType(int optionType) - This method allows you to set the
option type for the dialog.
and other
Cont…
Field of JOptionPane are
ERROR_MESSAGE - A Constant code displaying an error message
icon.
INFORMATION_MESSAGE - A Constant code displaying
information message icon
WARNING_MESSAGE - A Constant code for displaying Warning
message icon.
YES_NO_OPTION - A constant for creating a dialog with “Yes” and
“No” options.
YES_NO_CANCEL_OPTION - A constant for creating a dialog with
“Yes,” “No,” and “Cancel” options.
OK_CANCEL_OPTION - A constant for creating a dialog with “OK”
and “Cancel” options.
Sample of code
import javax.swing.*;
// Respond based on user's choice
import java.awt.event.ActionEvent;
if (response == JOptionPane.YES_OPTION) {
import java.awt.event.ActionListener;
JOptionPane.showMessageDialog(frame, "You chose YES!");
public class JOptionPaneWithButtonExample {
} else {
public static void main(String[] args) {
JOptionPane.showMessageDialog(frame, "You chose NO.");
// Create a JFrame (main window)
}
JFrame frame = new JFrame("JOptionPane with Button Example");
}
// Create a JButton
});
JButton button = new JButton("Click me for confirmation");
// Set up the JFrame layout
// Add ActionListener to the button
frame.setSize(300, 200); // Set the window size
button.addActionListener(new ActionListener() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit on
@Override close
public void actionPerformed(ActionEvent e) { frame.setLayout(null); // Set layout manager to null for absolute positioning
// Show a confirmation dialog when the button is clicked button.setBounds(50, 70, 200, 30); // Set button position and size
int response = JOptionPane.showConfirmDialog( frame.add(button); // Add button to frame
frame, // Parent component (the frame) // Make the frame visible
"Do you want to proceed?", // Message to display frame.setVisible(true);
"Confirmation", // Title of the dialog }
JOptionPane.YES_NO_OPTION, // Options (YES and }
NO)
);
Creating Menu Driven Java Application:
JMenuBar
jframe.setLayout(new FlowLayout());
jframe.setLayout(new
FlowLayout(FlowLayout.LEFT));
jframe.setLayout(new
FlowLayout(FlowLayout.RIGHT));
// jframe.setLayout(new
FlowLayout(FlowLayout.LEADING));
// jframe.setLayout(new
FlowLayout(FlowLayout.TRAILING));
// jframe.setLayout(new FlowLayout(FlowLayout.CENTER));
jframe.setLayout(new FlowLayout(FlowLayout.CENTER,
20, 20)); jframe.add(jbtn1);
jframe.add(jbtn2);
jframe.add(jbtn3);
jframe.add(jbtn4);
jframe.add(jbtn5);
jframe.add(jbtn6);
jframe.setSize(500, 500);
jframe.setVisible(true);
}
};
2. GridLayout
The GridLayout manager divides the container up into a given number of rows
and columns. All sections of the grid are equally sized and as large as possible.
GridLayout can be set using one of the constructors
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components
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.
Sample of code
import java.awt.*; import
javax.swing.*;
public class BorderLayoutDemo {
public stati c void main(String
args[ ] ) {
jframe.setLayout(new GridLayout());
jframe.setLayout(new GridLayout(2,3));
jframe.setLayout(new GridLayout(3,2,20,20));
jframe.add(jbtn1);
jframe.add(jbtn2);
jframe.add(jbtn3);
jframe.add(jbtn4);
jframe.add(jbtn5);
jframe.add(jbtn6);
jframe.setSize(500, 500);
jframe.setVisible(true);
}
}
3. BorderLayout
The BorderLayout manager divides the window into five areas: East, South, West,
North, and Center. At most five components can be added.
It has two constructor
BorderLayout():mcreates a border layout but with no gaps between the components.
BorderLayout(int horizontalgap, int verticalgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Sample of code
import java.awt.*; import
javax.swing.*;
public class
BorderLayoutDemo {
public stati c void
main(String args[]) {
Sample of code
JButton btn = new JButton(“Save”);
btn.addActionListener(new ActionListener())
public void actionperformed(ActionListener e){
system.out.print(“hellow”);
}
Cont…
Key Participants in event handling are
1. Source - an object that generates an event.
Occurs when an internal state of that object changes
in some way.
key in offering information about the event
occurred to handler
2. Listener - the event handler.
is an object that is notified when an event occurs.
is responsible for generating a response to an event .
Cont…
Event classes represent the event. Java provides various
Event classes
Event Class Description Listener
AWTEvent It is the root event class for all SWING events.
This class and its subclasses supercede the
original java.awt.Event class.
ActionEvent The ActionEvent is generated when the button ActionListener
is clicked or the item of a list is double-
clicked.
KeyEvent On entering the character the Key event is KeyListener
generated.
MouseEvent This event indicates a mouse action occurred in a MouseListener and
component. MouseMotionListener
WindowEvent The object of this class represents the change in WindowListener
the state of a window.
AdjustmentEvent The object of this class represents the AdjustmentListener
adjustment event emitted by Adjustable
objects.
ComponentEvent The object of this class represents the change in ComponentListener
the state of a window.
ContainerEvent The object of this class represents the change in ContainerListener
the state of a window.
PaintEvent The object of this class represents the change in PaintListener
the state of a window.
Reading assignment
The following are UI component