AWT & SWINGS IN JAVA
IMPLEMENTING GUIS IN JAVA
The Java Foundation Classes (JFC) are a set of
packages encompassing the following APIs:
Abstract Window Toolkit (AWT): native GUI
components
Swing: lightweight GUI components
2D: rendering two-dimensional shapes, text, and images
Accessibility: allowing compatibility with, for example,
screen readers and screen magnifiers
ABSTRACT WINDOW TOOLKIT (AWT)
Provides basic UI components:
Buttons, lists, menus, textfields, etc
Event handling mechanism
Clipboard and data transfer
Image manipulation
Font manipulation
Graphics
Platform independence is achieved through peers, or
native GUI components
AWT PACKAGES
java.awt Basic component functionality
java.awt.accessibility Assistive technologies
java.awt.color Colors and color spaces
java.awt.datatransfer Clipboard and data transfer support
java.awt.dnd Drag and drop
java.awt.event Event classes and listeners
java.awt.font 2D API font package
java.awt.geom 2D API geometry package
java.awt.im Input methods
java.awt.image Fundamental image manipulation classes
java.awt.peer Peer interfaces for component peers
java.awt.print 2D API support for printing
java.awt.swing Swing components
THE AWT LIBRARY
AWT is a general-purpose, multi-platform
windowing library.
It’s a standard part of Java environment.
Provides all the basic functionality that may be
needed for use in developing GUI application.
Provides classes that encapsulate many useful
GUI components.
AWT CLASS
import java.awt.*;
class MyFrame extends Frame
{
public void paint(Graphics g)
{
g.drawString(“Hello world”,50,50);
}
public static void main(String args[])
{
Frame f = new MyFrame();
f.setSize(100,100);
f.show();
}
}
THE COLOR CLASS
Defines methods & constants for manipulating
colors in a Java program.
Every color is created from a red, green & blue
component.
To change color, you must create a Color object or
use one of the predefined Color constants.
THE FONT CLASS
Allows to create a font object that will display
text in a particular font.
The number of fonts varies greatly across
systems.
Java uses standardized font names & maps these
into system-specific font names for portability.
THE COLOR & FONT CLASS
public void paint(Graphics g)
{
g.setColor(Color.blue);
Font f = new
Font(“TimesRoman”,Font.BOLD,20);
g.setFont(f);
g.drawString(“Hello World”, 50,50);
}
GRAPHICS CLASS
Graphics is an abstract class.
A graphics context enables drawing on screen in
Java.
A Graphics object encapsulates state info needed
for the basic rendering options that java supports.
It remembers a collection of settings for drawing
images &text.
All drawing in Java must go through a Graphics
object.
GRAPHICS CLASS
Why is Graphics class an abstract class ?
Reason is : Java’s Portability
Graphics capabilities that enable a PC running
windows are different from ones that enable a UNIX
workstation to draw a rectangle.
When Java is implemented on each platform, a
derived class of Graphics is created that actually
implements the drawing capabilities.
E.g. WGraphics class for Windows
AWT(COMPONENTS)
Button Canvas
Checkbox CheckboxGroup
Choice List
Menu Label
TextField TextArea
Scrollbar ScrollPane
COMPONENT HIERARCHY IN AWT
Object
Component Scrollbar
Canvas
Checkbox
Choice
Label
Text Component
Text Area
List
Text Field
Container
AWT (CONTAINER)
Component
Container
Panel Window
Frame Dialog
FileDialog
EXAMPLE: A SIMPLE FRAMED WINDOW
import java.awt.*;
import javax.swing.*;
public class SwingTest {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Frame");
frame.setSize(new Dimension(300,200));
frame.setLocation(100,100);
frame.setVisible(true);
}
}
JAVA
Swing Programming
SWING COMPONENTS
Swing is a collection of libraries that
contains primitive widgets or controls
used for designing Graphical User
Interfaces (GUIs).
Commonly used classes in javax.swing
package:
JButton, JTextBox, JTextArea, JPanel,
JFrame, JMenu, JSlider, JLabel, JIcon, …
There are many, many such classes to do
anything imaginable with GUIs
Here we only study the basic architecture and
do simple examples
SWING COMPONENTS, CONT.
Each component is a Java class with a fairly
extensive inheritency hierarchy:
Object
Component
Container
JComponent Window
JPanel Frame
JFrame
USING SWING COMPONENTS
Very simple, just create object from appropriate
class – examples:
JButton but = new JButton();
JTextField text = new JTextField();
JTextArea text = new JTextArea();
JLabel lab = new JLabel();
Many more classes. Don’t need to know every one
to get started.
See ch. 9 Hortsmann
ADDING COMPONENTS
Oncea component is created, it can be
added to a container by calling the
container’s add method:
Container cp = getContentPane(); This is required
cp.add(new JButton(“cancel”));
cp.add(new JButton(“go”));
How these are laid out is determined by the layout manager.
LAYING OUT COMPONENTS
Not so difficult but takes a little practice
Do not use absolute positioning – not very
portable, does not resize well, etc.
LAYING OUT COMPONENTS
Use layout managers – basically tells
form how to align components when
they’re added.
Each Container has a layout manager
associated with it.
A JPanel is a Container – to have
different layout managers associated with
different parts of a form, tile with JPanels
and set the desired layout manager for
each JPanel, then add components
directly to panels.
LAYOUT MANAGERS
Java comes with 7 or 8. Most common and easiest
to use are
FlowLayout
BorderLayout
GridLayout
Using just these three it is possible to attain fairly
precise layout for most simple applications.
SETTING LAYOUT MANAGERS
Veryeasy to associate a layout manager
with a component. Simply call the
setLayout method on the Container:
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
As Components are added to the container, the layout
manager determines their size and positioning.
EVENT HANDLING
WHAT ARE EVENTS?
Allcomponents can listen for one or more
events.
Typical examples are:
Mouse movements
Mouse clicks
Hitting any key
Hitting return key
etc.
Tellingthe GUI what to do when a
particular event occurs is the role of the
event handler.
ACTIONEVENT
In Java, most components have a special event
called an ActionEvent.
This is loosely speaking the most common or
canonical event for that component.
A good example is a click for a button.
To have any component listen for ActionEvents,
you must register the component with an
ActionListener. e.g.
button.addActionListener(new MyAL());
DELEGATION, CONT.
This is referred to as the Delegation Model.
When you register an ActionListener with a
component, you must pass it the class which will
handle the event – that is, do the work when the
event is triggered.
For an ActionEvent, this class must implement
the ActionListener interface.
This is simple a way of guaranteeing that the
actionPerformed method is defined.
ACTIONPERFORMED
The actionPerformed method has the
following signature:
void actionPerformed(ActionEvent)
The object of type ActionEvent passed to
the event handler is used to query
information about the event.
Some common methods are:
getSource()
object reference to component generating event
getActionCommand()
some text associated with event (text on button, etc).
ACTIONPERFORMED, CONT.
These methods are particularly useful when using
one eventhandler for multiple components.
SIMPLEST GUI
import javax.swing.JFrame;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}
}
ANOTHER SIMPLE GUI
import javax.swing.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.add(but1);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
ADD LAYOUT MANAGER
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.setLayout(new FlowLayout(FlowLayout.CENTER);
cp.add(but1);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
ADD CALL TO EVENT HANDLER
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.setLayout(new FlowLayout(FlowLayout.CENTER);
but1.addActionListener(new MyActionListener());
cp.add(but1);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
EVENT HANDLER CODE
class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(“I got clicked”, null);
}
}
ADD SECOND BUTTON/EVENT
class SimpleGUI extends JFrame{
SimpleGUI(){
/* .... */
JButton but1 = new JButton(“Click me”);
JButton but2 = new JButton(“exit”);
MyActionListener al = new MyActionListener();
but1.addActionListener(al);
but2.addActionListener(al);
cp.add(but1);
cp.add(but2);
show();
}
}
HOW TO DISTINGUISH EVENTS –LESS
GOOD WAY
class MyActionListener implents ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getActionCommand().equals(“Exit”){
System.exit(1);
}
else if (ae.getActionCommand().equals(“Click me”){
JOptionPane.showMessageDialog(null, “I’m clicked”);
}
}
GOOD WAY
class MyActionListener implents ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == b2){
System.exit(1);
}
else if (ae.getSource() == b1){
JOptionPane.showMessageDialog(null, “I’m clicked”);
}
}
Question: How are b1, b2 brought into scope to do this?
Question: Why is this better?