You are on page 1of 26

Java Course

Module 13 Swing

Module Objectives
At the end of this module, participants will be
able to:
Create custom GUI using the Java Swing API
Listen for and handle events from GUI
components

Agenda

AWT/Swing Framework
Creating and Displaying a Frame
Adding Components to a Container
Using Layout Managers
Creating Complex Layouts

AWT
Stands for Abstract Window Toolkit.
First generation windowing, graphics and user interface toolkit
for Java.
Acted as a thin abstraction layer over the platforms native user
interface.
GUI written using AWT will change its appearance to use the
native platforms look and feel.

Swing
Second generation windowing toolkit for Java.
Draws its own widgets and user interface elements instead of
relying on the native windowing system.
Has a greater amount of features and capabilities than AWT at
the cost of performance, complexity, and steeper learning curve.
Has the ability to alter its look-and-feel independent of the
underlying native windowing system.
Part of the J2SE since 1.2.

Swing API
The package javax.swing and its sub-packages contains the
necessary class files for the different Swing components, event
handlers, and various utilities.
Many elements from the AWT libraries under the package
java.awt are still in use by Swing.
Classes that belong to Swing typically starts with J to
differentiate them their AWT counterparts.
Ex: Frame (AWT) vs JFrame (Swing)

A Simple Frame
package sef.module14.sample;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Container;
public class SimpleJFrame extends JFrame{
private JLabel firstLabel;

public SimpleJFrame(){
firstLabel= new JLabel("First");
Container pane = getContentPane();
pane.add(firstLabel );
setLocation(300,300);
setSize(100,100);
setVisible(true);
}
public static void main(String arg[]){
SimpleJFrame frame = new SimpleJFrame();
}

Swing Imports
The following two lines import two classes from the Swing library
for use in our application.
import javax.swing.JFrame;
import javax.swing.JLabel;

JFrame represents a top level (can exist without a parent


container) window container with a few preset features and
functionalities, such as a title bar, an icon, and
minimize/maximize/close buttons.
JLabel is a simple component for displaying text.

Extending the JFrame


We create a class that extends the JFrame. This allows us to
customize the JFrame.
public class SimpleJFrame extends JFrame{
private JLabel firstLabel;
public SimpleJFrame(){
//Other code
firstLabel = new JLabel(First);
}
}

Customizing the JFrame


In the constructor, we add a label component to the frame
displaying a message to write on the frame.
Container pane = getContentPane();
firstLabel = new JLabel(First);
pane.add(firstLabel);

The getContentPane() method retrieves the object that


represents the JFrames container for other components.
The add() method adds the specified component to the
JFrames container according to the containers layout.

10

Customizing the JFrame (cont.)


setLocation(int x, int y) Sets the initial location of the JFrame
upon creation. The parameters represent x,y coordinates of the
upper left corner of the JFrame. Location 0,0 is the upper left
corner of the screen
setSize(int width, int height) Sets the initial dimensions of the
JFrame
setVisible(boolean visible) Sets the visibility of the JFrame. By
default, newly created JFrames are invisible.
** Refer to the SimpleJFrame.java sample code

11

Customizing the JFrame (cont.)


Compiling and running the application should show a small
window roughly at the center of your screen:

12

Using Layouts Managers


Swing containers use Layout Managers to determine the
position and dimension of the components inside a container.
Each layout is represented as a class.
To set the layout manager of a container, pass the instance of a
layout manager class as a parameter to a containers
setLayout() method.
** Refer to the LayoutFrameSample.java sample code

13

Setting the Layout Manager


The following modifications to the previous example will set the
layout manager to use FlowLayout.
Container pane = getContentPane();
FlowLayout flowLayout = new FlowLayout();
pane.setLayout(flowLayout);

The FlowLayout manager arranges components in a series from


left to right, top to bottom.
Modify the code to set the layout and add two more
components.

14

Add More Components


package sef.module14.sample;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Container;
import java.awt.FlowLayout;
public class LayoutFrameSample extends JFrame{
private JLabel firstLabel;
private JLabel secondLabel;
private JLabel thirdLabel;
public LayoutFrameSample(){
firstLabel= new JLabel("First");
secondLabel= new JLabel("Second");
thirdLabel= new JLabel("Third");
Container pane = getContentPane();
FlowLayout flowLayout = new FlowLayout();
pane.setLayout(flowLayout);
pane.add(firstLabel );
pane.add(secondLabel);
pane.add(thirdLabel);
setLocation(300,300);
setSize(100,100);
setVisible(true);
}
public static void main(String arg[]){
LayoutFrameSample frame = new LayoutFrameSample();
}
15

Using BorderLayout
The BorderLayout Manager divides the container into 5 distinct
zones named NORTH, SOUTH, EAST, WEST and CENTER.
When a component is added to the container, the code must
also specify where the component is to be placed.
The size of the component added will depend on the dimensions
of the container.
BorderLayout is the default Layout of the JFrame content pane.
** Refer to the BorderLayoutFrame.java sample code

16

Using BorderLayout (cont.)


package sef.module14.sample;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BorderLayoutFrame extends JFrame{
private JButton firstButton;
private JButton secondButton;
private JButton thirdButton;
private JButton fourthButton;
private JButton fifthButton;
public BorderLayoutFrame(){
firstButton= new JButton("First");
secondButton= new JButton("Second");
thirdButton= new JButton("Third");
fourthButton= new JButton("Fourth");
fifthButton= new JButton("Fifth");
Container pane = getContentPane();
pane.add(firstButton, BorderLayout.NORTH);
pane.add(secondButton, BorderLayout.SOUTH);
pane.add(thirdButton, BorderLayout.EAST);
pane.add(fourthButton, BorderLayout.WEST);
pane.add(fifthButton, BorderLayout.CENTER);
setLocation(300,300);
setSize(200,200);
setVisible(true);
}
public static void main(String arg[]){
BorderLayoutFrame frame = new BorderLayoutFrame();
}
}

17

Creating Complex Designs


There are other layouts with different features that can be used.
Individual layouts by themselves are very limited and are not
flexible enough to create complex GUI designs.
To create complex designs, a combination of different layouts
need to be used.
** Refer to the ComplexSample.java sample code

18

Combining Layouts
The JPanel class is a container that is designed to be placed
inside other containers.
JPanels can set their own layouts independently from the parent
container layout.
JPanels can be placed inside other JPanels.

19

Combining Layouts (cont.)


A Panel named leftPanel was created and JButtons added using
GridLayout set to have 1 column and 3 rows.
A Panel named bottomPanel was created and JButtons added
using GridLayout set to have 3 columns and 1 row
The leftPanel was set on the frames content pane on the west
section, the bottomPanel on the south

20

Event Handlers
Event handlers are used to add interactivity to GUIs.
All components are event sources that generate events like
mouse clicks and movement, keyboard input, etc.
Event listeners/handler are objects that want to be informed of
events generated by event sources and execute behavior when
an event is generated.
Event listeners are interfaces that are implemented by classes.
Each listener interface represents different possible kinds of
events.

21

Commonly Used Event Listeners


ActionListener Listens for ActionEvents such as button
clicks, text field entries, menu selections.
KeyListener Listens for key strokes.
MouseListener Listens for MouseEvents such as mouse
clicks, presses, and releases. Mostly used for pop-up menus.
MouseMotionListener Listens for mouse movements.
ChangeListener Listens for changes occurring in
components, such as sliders, progress bars, and spinners.
WindowListener Listens for WindowEvents, such as window
closing, focusing, iconifying, etc.

22

Registering Listeners
Identify the components that will act as the source of the events.
Identify the kind of events that these components might
generate in order to determine what kind of listener interfaces to
use.
Implement the listener methods.
Register an instance of the event handler classes to the
appropriate event sources.

** Refer to the ActionListenerFrame.java sample code

23

Using Anonymous Inner Classes


No need for listener interface to be implemented by main class.
ActionListener is implemented inside addActionListener().
Unlike the previous example, there is no need to identify the
event source.

24

Questions and Comments

25

Activity
1)
2)

3)
4)
5)
6)

Implement GUI application shown below and place


the files in sef.module14.activity
Create the GUI shown below:

Each slider has a value from 0 to 255


Moving each slider should update the corresponding
numeric label to its right
When the slider is updated the horizontal bar at the
bottom should update its background color depending
on the values of the sliders
The color is represented in standard RGB format

Hint:

JPanels by default are transparent. You can use their setOpaque() method to
change this.

The Color object can be used to represent a color.

You can use JSlider to render a slider and ChangeListener to monitor events.
26

You might also like