1 Introduction 2 Creating an interface - Department of Mathematics

snottybugbearSoftware and s/w Development

Nov 3, 2013 (4 years and 8 months ago)


Bachelor of Science (General) Degree (Level III)
Industrial Mathematics
MMA 3b23:Mathematical Computing Programming Project - Java
Lecture No:11 Swing Semester I,2008
1 Introduction
Awindow-based application is one with one or more windows that provide the interface between
the user and the application.These windows,and the environment that the user interacts with,
are known as the graphical user interface (GUI).
The fundamental elements that you need to create a GUI reside in two packages,java.awt
and javax.swing.Swing is a set of packages that enables graphical user interfaces and user
input with the mouse,keyboard,and other input devices.Swing is an extension of the Ab-
stract Windowing Toolkit (AWT) packages which de¯nes GUI elements,referred to as Swing
components,that provide much-improved alternatives to components de¯ned by classes in
The Swing classes are part of a more general set of GUI programming capabilities that are
collectively referred to as the Java Foundation Classes,or JFC for short.To use a Swing class,
you must make it available with an import statement:
import javax.swing.*;
All Swing components are subclasses of the abstract class JComponent.Before components
can be displayed in a user interface,they must be added to a container,component that can
hold other components.Swing containers,which can often be placed in other containers,are
subclasses of java.awt.Container.This class includes methods to add and remove compo-
nents from a container,arrange components using an object called a layout manager,and set
up borders around the edges of a container.
2 Creating an interface
A window is a container that can be displayed on a user's desktop.
Defines a component, which is an entity
that can be displayed (e.g. button)
Defines a basic window with no title
Defines a component that can contain
other components
Defines a window with a title bar and border
bar or border
The main interface object is either a simple window (the JWindow class) or a more special-
ized window called a frame (the JFrame class).
JFrame - This is used as the basic Java application window.An object of this class has
a title bar,border and provision for adding a menu.You can also add other components
to it.
JWindow - An object of this class type is a window with no title bar or window man-
agement icons:Maximize,Minimize,or Close buttons.These are are usually displayed
when a program is loading (Splash screens).
JComponent - The subclasses of JComponent de¯ne a range of standard components such
as menus,buttons,checkboxes,and so on.You'll use these classes to create the GUI for
your application or applet.
2.1 Creating a Window
You can display an application window simply by creating an object of type JFrame,calling a
method for the object to set the size of the window,and then calling a method to display the
You should handle the following tasks:
Call a superclass constructor to give the frame a title and handle other setup procedures:
The JFrame class has two constructors:JFrame() and JFrame(String).One sets the
frame's title bar to the speci¯ed text and the other leaves the title bar empty.You also
can set the title by calling the frame's setTitle(String) method.
Set the size of the frame's window:either by specifying the width and height in pixels.
The size of a frame can be established by calling the setSize(int,int) method with
the width and height as arguments.
Decide what to do if a user closes the window:The setDefaultCloseOperation()
method for the JFrame object determines what happens when you close the window
by either clicking on the X icon or selecting Close from the menu that is displayed when
you click on the Java icon in the top-left corner of the window.There are four possible
argument values you can use here:
CLOSE - Exit the application when the frame is closed.
CLOSE - Close the frame,remove the frame object from memory,and
keep running the application.
CLOSE - This makes the close operation for the frame window inef-
CLOSE - The default option:Close the frame and continue running.
Display the frame:Frames are invisible when they are created.You can make themvisible
by calling the frame's setVisible(boolean) method.The setVisible() method with
the argument set to true displays the application window on top of any other windows
that are currently visible on the screen.If you wanted to hide a window at some point
during the execution of an application,you would call setVisible() with the argument
set to false.
Code 1
Framing a Window
import javax.swing.JFrame;
public class MyFrame {
public static void main(String[] args) {
JFrame jf = new JFrame("This is the Frame title");//Step a)
jf.setSize(300,100);//Step b)
2 Continued.
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Step c)
jf.setVisible(true);//Step d)
You can do the same thing by subclassing JFrame and creating an object of the derived class:
import javax.swing.JFrame;
public class MyFrame extends JFrame {
public MyFrame(){
super("This is the Frame title");//Step a)
setSize(300,100);//Step b)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Step c)
setVisible(true);//Step d)
public static void main(String[] args) {
MyFrame jf = new MyFrame();
When a frame is displayed,the default behavior is for it to be positioned in the upper-left corner
of the computer's desktop.You can specify a di®erent location by calling the setBounds(int,
int,int,int) method.The ¯rst two arguments to this method are the (x,y) position of the
frame's upper-left corner on the desktop.The last two arguments set the width and height of
the frame.E.g.setBounds(50,100,300,100) would display the frame as:
Note 1
The screen coordinate system has the origin point,(0,0),at the top-left corner of the
screen,with the positive x-axis running left to right and the positive y-axis from top to bottom.
The positive y-axis in screen coordinates is therefore in the opposite direction to that of the
usual Cartesian coordinate system.The actual physical width and height of the window,as well
as its position relative to the edge of the screen,will depend on the size of your screen and the
display resolution.
Code 2
Creating a Window
Creating a window using JWindow is similar to working with frames in Swing,except that you
can't set titles,closing operations,etc.
3 Continued.
import javax.swing.JWindow;
public class MyWindow {
public static void main(String[] args) {
JWindow jw = new JWindow();
This will output a blank grey area without a border or title which can be used for displaying
some intro while the software is loading.
3 Basics of Components
Figure 1:Some user interface components
3.1 Component Attributes
The Component class de¯nes attributes,which record the following information about an object:
The position is stored as (x,y) coordinates.This ¯xes where the object is in relation to
its container in the coordinate system of the container object.
The name of the component is stored as a String object.
The size is recorded as values for the width and the height of the object.
The foreground color and background color that apply to the object.
The font used by the object when text is displayed.
4 Continued.
The cursor for the object - this de¯nes the appearance of the cursor when it is over the
Whether the object is enabled or not - when a component is enabled,its enabled state is
true,and it has a normal appearance.When a component is disabled it is grayed out.
² Whether the object is visible on the screen or not - if an object is not marked as visible,
it is not drawn on the screen.
Whether the object is valid or not - if an object is not valid,the layout of the entities
that make up the object has not been determined.
You can only modify the characteristics of a Component object by calling its methods or
a®ecting it indirectly in some way since none of the data members that store its characteristics
are directly accessible - they are all private.For example,you can change the name of a
Component object myWindow with the statement:myWindow.setName("The Name");
If you subsequently want to retrieve the name of an object,you can use the getName()
method,which returns the name as a String object.For example:String theName =
myWindow.getName();The isVisible(),isEnabled(),and isValid() methods return true
if the object is visible,enabled,and valid,respectively.You can set an object as visible
or enabled by passing the value true as an argument to the methods setVisible() and
You can set size and position,background/foreground colors,cursors,fonts,etc.
3.2 Swing Components
All the Swing component classes are de¯ned in the javax.swing package and have class names
that begin with J.
3.2.1 JButton
The JButton represents clickable buttons
that you would use as a dialog button - OK
and Cancel buttons.A Swing button can fea-
ture a text label,a graphical icon,or both.
Constructors have the form:
JButton(button name/icon)
E.g.JButton save = new JButton("Save")
3.2.2 JLabel
The most elementary text component is a
JLabel object.A JLabel component is pas-
sive and does not react to input events so you
can't edit it.A label is a user component
that holds text,and icon,or both.Labels,
which are created from the JLabel class,are
often used to identify the purpose of other
components on an interface.They cannot be
directly edited by a user.Constructors have
the form:You can also specify an alignment.
JLabel(label name/icon)
E.g.JLabel save = new JLabel("This is a Label:")
3.2.3 JTextField
A JTextField component looks similar to
a label in that it displays a single line of text,
but in this case it is editable.Constructors
have the form:You can also specify a default
value and length.
JTextField username = new JTextField()
E.g.JTextField username = new JTextField("user",10);
5 Continued.
3.3 Adding Components to a Container
Before you can display a user interface component such as a button in a Java program,you
must add it to a container and display that container.
To add a component to a container,call the container's add(Component) method with the
component as the argument.
The simplest Swing container is a panel (the JPanel class).The following example creates
a button and adds it to a panel:
JButton save = new JButton("Save");
JPanel panel = new JPanel();
Finally add the panel to the frame.
Remember to do this before setting setVisible() true or the button won't show up.Full
code is as follows:
Code 3
Adding a button
import javax.swing.*;
public class MyButton {
public static void main(String[] args) {
JFrame jf = new JFrame("This is the Frame title");
JButton save = new JButton("Save");
JPanel panel = new JPanel();
Note 2
If you click the button,absolutely nothing happens.Doing something response to a
button click is covered in Event Handling.
Implement the following user interface:
6 Last Page