Download - M13 - Swing
-
8/10/2019 M13 - Swing
1/26
Module 13Swing
Java Course
-
8/10/2019 M13 - Swing
2/26
2
Module Objectives
At the end of this module, participants will beable to:
Create custom GUI using the Java Swing API
Listen for and handle events from GUI
components
-
8/10/2019 M13 - Swing
3/26
3
AWT/Swing Framework
Creating and Displaying a Frame
Adding Components to a Container
Using Layout Managers Creating Complex Layouts
Agenda
-
8/10/2019 M13 - Swing
4/26
4
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.
-
8/10/2019 M13 - Swing
5/26
5
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.
-
8/10/2019 M13 - Swing
6/26
6
Swing API
The packagejavax.swing and its sub-packages contains thenecessary class files for the different Swing components, event
handlers, and various utilities.
Many elements from the AWT libraries under the package
java.awtare 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)
-
8/10/2019 M13 - Swing
7/267
A Simple Framepackage 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();
}}
-
8/10/2019 M13 - Swing
8/268
Swing Imports
The following two lines import two classes from the Swing libraryfor 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.
-
8/10/2019 M13 - Swing
9/269
Extending the JFrame
We create a class that extends the JFrame. This allows us tocustomize the JFrame.
public class SimpleJFrame extends JFrame{
private JLabel firstLabel;
public SimpleJFrame(){
//Other code
firstLabel = new JLabel(First);
}
}
-
8/10/2019 M13 - Swing
10/2610
Customizing the JFrame
In the constructor, we add a label component to the framedisplaying 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.
-
8/10/2019 M13 - Swing
11/26
11
Customizing the JFrame (cont.)
setLocation(int x, int y)Sets the initial location of the JFrameupon 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
-
8/10/2019 M13 - Swing
12/26
12
Customizing the JFrame (cont.)
Compiling and running the application should show a smallwindow roughly at the center of your screen:
-
8/10/2019 M13 - Swing
13/26
13
Using Layouts Managers
Swing containers use Layout Managers to determine theposition 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
-
8/10/2019 M13 - Swing
14/26
14
Setting the Layout Manager
The following modifications to the previous example will set thelayout 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 morecomponents.
-
8/10/2019 M13 - Swing
15/26
15
Add More Componentspackage 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();
}
-
8/10/2019 M13 - Swing
16/26
16
Using BorderLayout
The BorderLayout Manager divides the container into 5 distinctzones 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
-
8/10/2019 M13 - Swing
17/26
17
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();
}}
-
8/10/2019 M13 - Swing
18/26
18
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
-
8/10/2019 M13 - Swing
19/26
19
Combining Layouts
The JPanel class is a container that is designed to be placedinside other containers.
JPanels can set their own layouts independently from the parent
container layout.
JPanels can be placed inside other JPanels.
-
8/10/2019 M13 - Swing
20/26
20
Combining Layouts (cont.)
A Panel named leftPanel was created and JButtons added usingGridLayout 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
-
8/10/2019 M13 - Swing
21/26
21
Event Handlers
Event handlers are used to add interactivity to GUIs. All components are event sou rces that generate eventslike
mouse clicks and movement, keyboard input, etc.
Event l is teners/handlerare 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.
-
8/10/2019 M13 - Swing
22/26
22
Commonly Used Event Listeners
ActionListenerListens for ActionEvents such as buttonclicks, text field entries, menu selections.
KeyListenerListens for key strokes.
MouseListenerListens for MouseEventssuch as mouse
clicks, presses, and releases. Mostly used for pop-up menus.
MouseMotionListenerListens for mouse movements.
ChangeListenerListens for changes occurring in
components, such as sliders, progress bars, and spinners.
WindowListenerListens for WindowEvents,such as window
closing, focusing, iconifying, etc.
-
8/10/2019 M13 - Swing
23/26
23
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
-
8/10/2019 M13 - Swing
24/26
24
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.
-
8/10/2019 M13 - Swing
25/26
25
Questions and Comments
-
8/10/2019 M13 - Swing
26/26
26
Activity
1) Implement GUI application shown below and place
the files in sef.module14.activity2) Create the GUI shown below:
3) Each slider has a value from 0 to 2554) Moving each slider should update the corresponding
numeric label to its right
5) When the slider is updated the horizontal bar at thebottom should update its background color dependingon the values of the sliders
6) The color is represented in standard RGB format
Hint:
JPanels by default are transparent. You can use their setOpaque() method tochange this.
The Color object can be used to represent a color.
You can use JSlider to render a slider and ChangeListener to monitor events.