Java Graphical User Interface
JFC or Java Foundation Classes, is a set of Graphical User Interface (GUI) support
packages that are available as part of the Java SE platform and which became core
application program interfaces (API’s) in JDK 1.2 and later version. JFC includes the
following features:
• The Swing component set – Swing is an enhanced components set that
provides replacement components for those in AWT and a number of more
advanced components.
• 2D graphics – using the Java 2D API, you can perform advanced drawing,
complex color manipulations, shape and transformation (rotate, shear, stretch, and
so forth) handling, and treat text as shapes that can be manipulated. 2D graphics
are not discussed in this course.
• Pluggable look-and-feel. This feature provides Swing components a choice of
look look-and-feel. The same program can be rendered in Microsoft Windows,
Motif, and Metal look-and-feel formats.
• Accessibility – National governments are increasingly mandating that computer
programs used in their departments are accessible to those with disabilities. The
Swing component set facilitates such programming by means of the accessibility
API’s. It provides interfaces for associate technologies, such as screen reader,
screen magnifiers, audible text reader (speech processing), and so on.
• Drag-and-Drop – GUI-based data transfer, both between elements of one
program and between different programs, has been a feature of modern GUI
systems for a number of years. This type of transfer falls into two forms from the
user’s point of view. These are cut-and-paste and drag-and-drop. The Java JDK
releases include support for both these communications media.
• Internationalization – the JFC classes support different character set such as
Japanese, Chinese, and Korean. Chinese, and Korean. This allows developers to
build applications that can interact with users worldwide in their own languages.
What is a Swing?
Swing is an enhanced components set that provides replacement components for those
in the original AWT and a number of more advanced components. These components
enable you to create user interfaces with the type of functionality that has become
expected in modern applications. Such components include trees, tables, advanced text
editors, and tear-off-tool bars.
Swing also has special features. For example, using Swing, you can write a program that
adopts either the look-and-feel of the host platform or that uses a common look-and-feel
written especially for the Java programming language. In fact, you can create your own
look-and-feel from scratch, or and modify existing one and plug it into your program,
either hard-coded or by user or system administrator selecting a look-and-feel at runtime.
Pluggable Look-and-Feel
Pluggable look-and-feel enables developers to build applications that execute on any
platform as if they were developed for that specific platform. A program executed in the
Microsoft Windows environment appears as if it was developed for this environments;
and the same program executed on the UNIX platform appears as if it was developed for
the UNIX environment
Developers can create their own custom Swing components. With any kind of look-and
feel that they choose to design. This increases the consistency of applications and
applets deployed across platforms. An entire application’s GUI can switch form one look-
and-feel to a different one at runtime.
Swing Architecture
Swing components are designed based on the Model-View-Controller (MVC)
architecture. The Swing architecture is not strictly based on the MVC architecture but has
its roots in the MVC.
Model-View-Controller Architecture
According to the MVC architecture, a component can be modelled as three separate
parts as shown in the figure.
Model – The model stores the data used to define the component.
View – The view represents the visual display of the component. This display is
governed by the data in the model.
Controller – the controller deals with the behavior of the components when a user
interacts with it. This behavior can include any updates to the model or view.
Theoretically, these three types of architecture (Model, View, Controller) should be
represented by different class types. But, practically, this turns out to be very difficult
because of the dependencies between the view and the controller. The role of the
controller is heavily dependent on the implementation of the view, because the user
interacts with the view. In other words, it is difficult to write a generic controller,
independent of the implementation of the view. This issue is addressed by the separable
model architecture.
Separable Mode Architecture
The Swing components follow a separable model architecture. In this architecture the
view and the controller are merged as a single composite object, because of their tight
dependency on each other. The model object is treated as a separate object just like in
MCC architecture as shown in the figure.
The UI Object is referred to as UI delegate. With this architecture it is possible to
delegate a few responsibilities of the component to an independent UI Object. This
explains how the pluggable look-and-feel is facilitated by the Swing components. The
components make the visual appearance of the components the responsibility of the
independent UI Object. So the UI Object of the installed look-and-feel is responsible for
the components look-and-feel.
Swing Packages
Packages Purpose
javax.accessibility Contains classes and interfaces that can be used to
allow assistive technologies to interact with Swing
components. Assistive technologies cover a broad range
of items, from audible text readers to screen
magnification. Although the accessibility classes are
technically not part of Swing, they are used extensively
throughout the Swing components.
javax.swing Contains the core Swing components, including most of
the model interfaces and support classes.
javax.swing.border Contains the definitions for the abstract border class as
well as eight predefined borders. Borders are not
components; instead, they are special graphical
elements that Swing treats as properties and places
around components in place of their insets. If you wish
to create your own border, you can subclass one of the
existing borders in this package, or you can code a new
one from scratch.
javax.swing.colorchooser Contains support for the JColorChooser component.
javax.swing.event Defines several new listeners and events that Swing
components use to communicate asynchronous
information between classes. To create your own
events, you can subclass various events in this package
or write your own event class.
javax.swing.filechooser Contains support for the JFileChooser component.
javax.swing.pending Contains an assortment of components that aren’t ready
for prime time, but may be in the future
javax.swing.plaf Defines the unique elements that make up the pluggable
look-and-feel for each Swing component. Its various
subpackages are devoted to rendering the individual
look-and-feels for each component on a platform-
byplatform basis. (Concrete implementations of the
Windows and Motif L&Fs are in subpackages of
com.sun.java.swing.plaf.)
javax.swing.table Provides models and views for the table component.
The table component allows you to arrange various
information in a grid-based format with an appearance
similar to a spreadsheet. Using the lower-level classes,
you can manipulate how tables are viewed and selected,
as well as how they display their information in each cell.
javax.swing.text Provides scores of text-based classes and interfaces
supporting a common design known as document/view .
javax.swing.text.html Used specifically for reading and formatting HTML text
through an ancillary editor kit.
javax.swing.text.html.parser Contains support for parsing HTML.
javax.swing.text.rtf Used specifically for reading and formatting the Rich
Text Format (RTF) text through an ancillary editor kit.
javax.swing.tree Defines models and views for a hierarchal tree
component, such as you might see representing a file
structure or a series of properties.
javax.swing.undo Contains the necessary functionality for implementing
undoable functions.
Swing Component Hierarchy
The Composition of a Java Technology GUI
A Swing API-based GUI is composed of the following elements.
Containers
Containers are on top of the GUI containment hierarchy. All the components in the
GUI are added to these container. JFrame, JDialog, JWindow, and JApplet are the
top level containers.
Components
All the GUI components are derived from the JComponent class, for example,
JComboBox, JAbstractButton, and JTextComponent.
Layout Manager
Layout managers are responsible for laying out components in a container.
BorderLayout, FlowLayout, GridLayout are a few examples of the layout manager.
There are more sophisticated and complex layout managers that give more
control over the GUI.
Swing Containers.
Swing container can be classified into three main categories
o Top-level containers o General-purpose containers o
Special-purpose containers
Top-level Containers
The top-level container are at the top of the Swing containment hierarchy. There
are three top-level containers: JFrame, JWindow, and JDiaglog. There is also a
special class, JApplet, which, while not strictly a top-level container.
Top-Level Container Hierarchy
Swing Components
Swing GUIs use two kinds of classes: GUI classes and non-GUI support classes. The
GUI classes are visual and descendants of JComponent, and are call J classes. The
non-GUI classes, however, they do not produce any visual output.
Swing components primarily provide components for text handling, buttons, labels, lists,
panes, combo boxes, scroll bars, scroll panes, menus, tables, and trees. Swing
components can be broadly classified as:
Buttons
Text components
Uneditable information display components
Menus
Formatted display components
Other basic controls
Swing Component Hierarchy
Properties of Swing Components
Common Component Properties
All the Swing components share some common properties because they all extend the
JComponent class as shown in the table.
Property Methods
Border Border getBorder() void
setBorder (Border b)
Background and void setBackground (Color bg) void
foredground color setBackground (Color bg)
Font void setFont (Font f)
Opaque void setOpaque (boolean isOpaque)
Maximum and minimum void setMaximumSize (Dimension d)
size void setMinimumSize (Dimension d)
Alignment void setAlignmentX (float ax) void
setAlignmentX (float ax)
Preferred size void setPreferredSize (Dimension ps)
Component-Specific Properties
This section discusses component properties specifically taking JComboBox as an
example. JComboBox inherits all the properties in JComponet and defines more
specific properties.
Properties Methods
Maximum row count void setMaximumRowCount (int count)
Model void setModel (ComboBoxModel cbm)
Selected index int getSecletedIndex()
Select Item Object getSelectedItem()
Item count int getItemCount()
Renderer void setRenderer (ListCellRenderer ar)
Editable void setEditable (boolean flag)
Layout Managers
A layout managers determines the size and position of the components within a
container. The alternative using layout managers is absolute positioning by pixel
coordinates. Absolute positioning is achieved through setting a container’s layout
property to null. Absolute positioning is not platform-portable. Issues such as the sizes of
fonts and screens ensure that a layout that is correct based on coordinates can
potentially be unusable on other platforms.
Unlike absolute positioning, layout managers have mechanism to cope with the following
situations:
The resizing of the GUI by the user
Different fonts and font sizes used by different operation systems or by user
customization
The text layout requirements of the different international locales (left-right,
rightleft, vertical)
To cope with these situations, layout managers lay out components according toa
predetermined policy. For example, the policy of the GridLayout is to position child
components in equal-sized cells, starting at the top left and working left to right, top to
bottom until the grid is full.
The BorderLayout Layout Manager
BorderLayout arranges the components in five different regions: CENTER, NORTH,
SOUTH, EAST, and WEST. The border layout manager limits the number of components
added to each region to one.
The position of the component should be specified. If no position is specified, by default
the component is added to the CENTER. All the extra space left is used by the
component in the CENTER.
BorderLayout is the default layout for JFrame, JDialog, and JApplet. The sample program
uses border layout.
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class BorderExample{
5
6 private JFrame f;
7 private JButton bn, bw, bc, bs, be;
8
9 public BorderExample(){
10
11 f = new JFrame("Border Layout");
12 bn= new JButton("Button1");
13 bc= new JButton("Button2");
14 bw= new JButton("Button3");
15 bs= new JButton("Button4");
16 be= new JButton("Button5");
17 }
18
19 public void launchFrame(){
20
21 f.add(bn, BorderLayout.NORTH);
22 f.add(bs, BorderLayout.SOUTH);
23 f.add(bw, BorderLayout.WEST);
24 f.add(be, BorderLayout.EAST);
25 f.add(bc, BorderLayout.CENTER);
26 f.pack();
27 f.setVisible(true);
28 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
29 }
30 }
31 public class BorderMain {
32 public static void main (String []args){
33 BorderExample guiWindow2 = new BorderExample();
34 guiWindow2.launchFrame();
35
36 }
37 }
Discussions:
Line 1 and Line 2 is an import declaration of GUI Libraries AWT and Swing components.
There are some components in AWT that is not carried out in the new versions Swing
GUI components that is why AWT is still need to be imported.
Line 6 and Line 7 is a variable declarations for the objects to be created in the GUI.
Line 11 is the name of your frame.
Line 9 to Line 17 is a constructor for the frame and physical object in the GUI (in this
sample 5 buttons were created).
Line 19 to Line 29 is a method created to set the Layout of the physical objects of the
GUI.
Line 26 is written in order for the settings to take effect
Line 27 set the GUI to be visible. We can also set the GUI into non-visilble by doing the
opposite (false).
Line 28 is used in order for the program to exit when the X button at the upper-right
corner of the GUI is click.
Output:
The FlowLayout Layout Manager
FlowLayout arranges the components I a row. By default, it arranges the components
from LEFT_TO_RIGHT. This orientation can be changed using the
ComponentOrientation property RIGHT_TOLEFT. The vertical and horizontal spacing
between the components can be specified. If not, the default vertical and horizontal gap
of five units is used.
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class FlowExample{
5
6 private JFrame f;
7 private JButton b1;
8 private JButton b2;
9 private JButton b3;
10 private JButton b4;
11 private JButton b5;
12
13 public FlowExample(){
14
15 f = new JFrame("FlowLayout Example");
16 b1= new JButton("Button1");
17 b2= new JButton("Button2");
18 b3= new JButton("Button3
19 b4= new JButton("Button4");
20 b5= new JButton("Button5");
21 }
22
23 public void launchFrame(){
24
25 f.setLayout(new FlowLayout());
26 f.add(b1);
27 f.add(b2);
28 f.add(b3);
29 f.add(b4);
30 f.add(b5);
31 f.pack(); //for the setting to take effect
32 f.setVisible(true);
33 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
34 }
35 }
36 public class FlowMain {
37 public static void main (String []args){
38
39 guiWindow2.launchFrame();
40
41 }
42 }
Discussions:
Line 1 and Line 2 is an import declaration of GUI Libraries AWT and Swing components.
There are some components in AWT that is not carried out in the new versions Swing
GUI components that is why AWT is still need to be imported.
Line 6 to Line 11 is a variable declarations for the objects to created in the GUI.
Line 13 to Line 21 is a constructor for the frame and physical object in the GUI(in this
sample 5 buttons were created).
Line 15 is the name of your frame.
Line 23 to Line 35 is a method created to set the Layout of the physical objects of the
GUI.
Line 31 is written in order for the settings to take effect
Line 32 set the GUI to be visible. We can also set the GUI into non-visilble by doing the
opposite(false).
Line 33 is used in order for the program to exit when the X button at the upper-right
corner of the GUI is click.
Output:
The GridLayout Layout Manager
GridLayout arranges the components in row and columns. Each component occupies the
same amount of space in the container. When creating a grid layout, the number of rows
and colimns should be specified. If not specified, by default, the layout mangaer creates
one rows and one column. The vertical gap and the horizontal gap between the
components can also be specified.
1 public class GridExample{
2
3 private JFrame f;
4 private JButton bn, bw, bc, bs, be;
5
6 public GridExample(){
7 f = new JFrame("Grid Layout");
8 bn= new JButton("Button1");
9 bc= new JButton("Button2");
10 bw= new JButton("Button3
11 bs= new JButton("Button4");
12 be= new JButton("Button5");
13 }
14
15 public void launchFrame
16
17 f.setLayout(new GridLayout(3,2));
18 f.add(bn);
19 f.add(bc);
20 f.add(bw);
21 f.add(bs);
22 f.add(be);
23 f.pack();
24 f.setVisible(true);
25 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
26 }
27 }
28 public class GridMain {
29 public static void main (String []args){
30 GridExample guiWindow2 = new GridExample();
31 guiWindow2.launchFrame();
32
33 }
34 }
Discussions:
Line 1 and Line 2 is an import declaration of GUI Libraries AWT and Swing components.
There are some components in AWT that is not carried out in the new versions Swing
GUI components that is why AWT is still need to be imported.
Line 3 and Line 4 is a variable declarations for the objects to create in the GUI.
Line 6 to Line 13 is a constructor for the frame and physical object in the GUI(in this
sample 5 buttons were created).
Line 7 is the name of your frame.
Line 15 to Line 26 is a method created to set the Layout of the physical objects of the
GUI.
Line 23 is written in order for the settings to take effect
Line 24 set the GUI to be visible. We can also set the GUI into non-visilble by doing the
opposite(false).
Line 25 is used in order for the program to exit when the X button at the upper-right
corner of the GUI is click.
Output:
Activity No. 5
Instructions:
1. Just rewrite the codes and made your modification(e.g. Background, font, and text)
to the Graphical user interface being shown in the 3 examples above. Rename
each frame to your FAMILYNAME. Please also add more components that you
want to try. For some other component and component properties please refer to
the reading material Java Foundation Classes.
2. In your point of modification (line where modification is done) please do make a
comments line for my reference of your modification.
3. Submit your answer in a pdf file(Filename is your
FAMILYNAME_FIRSTNAME_COURSE YEAR-SECTION). Answer should contain
the full source code and GUI output to this link not later than January 2, 2025.