Вы находитесь на странице: 1из 140



POUL KLAUSEN

JAVA 2: PROGRAMS
WITH A GRAPHICAL
USER INTERFACE
SOFTWARE DEVELOPMENT

2
Java 2: Programs with a graphical user interface: Software Development
1st edition
© 2017 Poul Klausen & bookboon.com
ISBN 978-87-403-1643-8
Peer review by Ove Thomsen, EA Dania

3
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Contents

CONTENTS
Foreword 6

1 Introduction 8

2 Hello Swing 10
Exercise 1 17
Exercise 2 22

3 Fonts and colors 29


Exercise 3 33

4 Dialog boxes 34
Exercise 4 44

5 More components 48
Exercise 5 62

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

4
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Contents

6 Layout and the component’s size 65


6.1 The component’s size 65
6.2 Borderlayout 68
6.3 Flowlayout 70
6.4 Gridlayout 72
Exercise 6 74
6.5 Gridbaglayout 76
Exercise 7 88
6.6 Boxlayout 89
Exercise 8 97
6.7 Null layout 98
Problem 1 100
6.8 MVC 101

7 Paedit 103
7.1 The model 103
7.2 The view 106

8 Final example 120


8.1 the program’s classes 121
8.2 Programming 123

9 A last example 128


9.1 Creating the library 128
9.2 The test program 134

5
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Contents

FOREWORD
This book is the second in a series of books on software development. The programming
language is Java, and the language and its syntax and semantics fills obviously much, but the
books have also largely focus on the process and how to develop good and robust applications.
The subject of the current book is an introduction to development of programs with a
graphical user interface and thus also an introduction to Swing. Programs with a graphical
user interface is also called GUI programs and Swing is the Java’s API for the development
of GUI programs. Swing is extensive and is first treated in detail in the book Java 9, and
the goal of the current book is to present as much of Swing, that the reader will be able to
write small applications that have practical interest. The book assumes a basic knowledge of
Java corresponding to the book Java 1 of this series, but since the objective is that the reader
soon should be introduced to the development of programs with a graphical user interface
the book bypasses many object-oriented concepts, which naturally are part of a book about
GUI programming. These concepts are discussed in detail in the next book in the series.

As the title says this series of books deals with software development, and the goal is to
teach the reader how to develop applications in Java. It can be learned by reading about
the subject and by studying complete sample programs, but most importantly by yourself
to do it and write your own programs from scratch. Therefore, an important part of the
books is exercises and problems, where the reader has to write programs that correspond to
the substance being treated in the books. All books in the series is built around the same
skeleton and will consist of text and examples and exercises and problems that are placed
in the text where they naturally belongs. The difference between exercises and problems is
that the exercises largely deals with repetitions of the substance that is presented in the text,
and furthermore it is relatively accurately described what to do. Problems are in turn more
loosely described, and are typically a little bigger and there is rarely any clear best solution.
These are books to be read from start to finish, but the many code examples, including
exercises and problems plays a central role, and it is important that the reader predict in
detail studying the code to the many examples and also solves the exercises and problems
or possibly just studying the recommended solutions.

All books ends with one or two larger sample programs, which focus primarily is on process
and an explanation of how the program is written. On the other hand appears the code only
to a limited extent – if at all – and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the development of programs
that are larger than the examples, which otherwise is presented, the aim of the concluding
examples also is to show program examples from varying fields of application.

6
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Contents

Most books also ends with an appendix dealing with a subject that would not be treated
in the books. It may be issues on the installation of software or other topics in computer
technology, which are not about software development, but where it is necessary to have
an introductory knowledge. If the reader already is familiar with the subject, the current
appendix can be skipped.

The programming language is, as mentioned Java, and besides the books use the following
products:

-- NetBeans as IDE for application development


-- MySQL to the extent there is a need for a database server (from the book Java 6
onwards)
-- GlassFish as a web server and application server (from the book Java 11 onwards)

It is products that are free of charge and free to install, and there is even talk about products,
where the installation is progressing all by itself and without major efforts and challenges.
In addition, there are on the web detailed installation instructions for all the three products.
The products are available on Windows and Linux, and it therefore plays no special role if
you use Linux or Windows.

All sample programs are developed and tested on machines running Linux. In fact, it plays
no major role, as both Java and other products work in exactly the same way whether the
platform is one or the other. Some places will be in the books where you could see that
the platform is Linux, and this applies primarily commands that concerning the file system.
Otherwise it has no meaning to the reader that the programs are developed on a Linux
machine, and they can immediately also run under Windows unless a program refers to
the file system where it may be necessary to change the name of a file.

Finally a little about what the books are not. It is not “how to write” or for that matter
reference manuals in Java, but it is as the title says books on software development. It is
my hope that the reader when reading the books and through the many examples can find
inspiration for how to write good programs, but also can be used as a source collection
with a number of examples of solutions to concrete everyday programming problems that
you regularly face as a software developer.

7
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Introduction

1 INTRODUCTION
This book is an introduction to writing GUI applications in Java using the Swing API. Far
from everything is treated, but conversely sufficient that you after reading the book can
write small applications with a graphical user interface.

A program with a graphical user interface is a program that runs in a window. Since it
is largely based on the principles of object-oriented programming, the topic should be
examined only after the next book in the series of this books, and the following will also
use a lot about classes and interfaces that are first mentioned there. When I still have chosen
to address the subject now, it is because I want to be able to write applications that are
more interesting and better match the programs that you meet in everyday life, than what
is possible purely as commands or console applications.

To write a program with a graphical user interface you must work on basis of a wide range
of finished classes, for example classes that creates and opens a window, classes representing
a button, classes for an input field, etc. These are very many classes, and they are assembled
in an API called Swing. In fact, Swing classes are based on an older API called AWT, so
there are two APIs that you have to learn about, and each of these has several packages
of classes. In the following I will call programs with a graphical user interface for GUI
programs where GUI stands for Graphical User Interface, and I will start to make it clear
that you can not learn to write GUI applications by learning all the many classes and
their methods. Instead, you must learn some basic principles for the development of these
kinds of programs, and once you have learned it, it’s all not so difficult. You quickly get
an idea of what it takes, and the question is what it’s all are called and what you actually
have to write. Here, however, there is only one way and that is to turn up the help, which
fortunately is online available and there is also a variety of other sources on the Internet
that provides advice on how to solve specific problems.

It is very different to writing GUI applications than console applications, and immediately
it seems as if you have to write a lot and you also has to (at least as I will introduce Swing),
but you will also quickly find that there is a lot of repetition and it is the same you have to
write every time. Therefore, to reducing the task after you’ve written the first programs, and
to reduce the work, you can create your own class library with frequently used methods.
You will find an example of that in the book’s appendix.

8
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Introduction

A GUI application will typically consist of several or many classes, but starting you can
think of each window as a class. In addition, the data that a program must treat, are usually
also be defined using classes, and possibly there will also be classes that implement the logic
that must process the application’s data. It is primarily in this context, that I am missing
something of the theory of classes and interfaces, as first is explained in the third book on
object-oriented programming. The following will therefore to some extent deal with object-
oriented concepts, but so that I postpone all details for later.

The focus is on how to write a GUI application using Swing, and I will mainly use the
most basic components, while more complex components is delayed. The goal is that after
reading this book and in detail studied the related examples and solved the related exercises
and problems you should be able to write less GUI programs for practical use.

9
JAVA
JAVA 2: 2: PROGRAMS
PROGRAMS WITH
WITH AA
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Hello
Hello swIng
Swing

2 HELLO
2 HELLOSWING
SWING
I’llI’llstart
starta alittle,
little,like
likeI Idid
didininthe
thefirst
firstbook
booktotowritewritea asimple
simpleprogram,
program,but butthis
thistime
timea a
programwhich
program whichopens opensa awindow
windowwherewhereyou youcan
canenter
entera aname.
name.When
Whenyou youthen
thenclick
clickthe
the
Addbutton,
Add button,the theentered
enteredname
nameis isadded
addedtotoa alistlistbox,
box,and
andyouyoucan
canenter
entera anew
newname.
name.AtAt
thebottom
the bottomofofthe thewindow,
window,there
thereis isalso
alsoa abutton,
button,allowing
allowingyouyoutotodelete
deletethe
thecontents
contentsofof
thelistlistbox.
the box.

InInaddition
additionyou youcan, can,what
whatyou youelse
elsecan
canwith
witha awindow.
window.You Youcan canmove
movethethewindow,
window,andand
youyoucan canchange
changethe thewindow
windowsize. size.Right-clicking
Right-clickingononthe
thetitle
titlebar,bar,you
youget
getthe
theusual
usualmenu
menu
andanddouble-click
double-clickatatthe thetitle
titlebar,
bar,the
thewindow
windowmaximizes.
maximizes.If Ifforfora amoment
momentyou youthink
thinkabout
about
it,it,it’sit’sactually
actuallya alotlotthat
thatthetheprogram
programcan cando.
do.

Forwriting
For writingthetheprogram
programI Ihave
haveininNetBeans
NetBeanscreated createda acommon
commonproject
projectininthe
thesame
sameway way
asasininthe
thefirst
firstbook,
book,and
andI Ihave
havecalled
calledthe theproject
projectHelloSwing.
HelloSwing.Next,
Next,I Iadded
addeda aclass
classtotothe
the
project,called
project, calledMainWindow,
MainWindow,and andit itis isthe
thefile
fileforforthis
thisclass,
class,which
whichcontains
containsallallthe
thecode:
code:

package helloswing;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MainWindow extends JFrame


{
private JTextField txtName = new JTextField();
private JButton cmdAdd = new JButton("Add");
private JButton cmdClr = new JButton("Clear");
private JList lstNames;
private DefaultListModel model = new DefaultListModel();

10 10
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Hello Swing
GRAPHICAL USER INTERFACE Hello swIng

public MainWindow()
{
setTitle("Hello Swing");
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addListeners();
createWindow();
setVisible(true);
}

private void createWindow()


{
add(createLabel(), BorderLayout.NORTH);
add(createLabel(), BorderLayout.WEST);
add(createLabel(), BorderLayout.EAST);
add(createLabel(), BorderLayout.SOUTH);
JPanel panel = new JPanel(new BorderLayout());
panel.add(createTop(), BorderLayout.NORTH);
panel.add(createBottom(), BorderLayout.SOUTH);
panel.add(createCenter());
add(panel);
}

private JLabel createLabel()


{
JLabel label = new JLabel("");
label.setPreferredSize(new Dimension(10, 10));
return label;
}

private JPanel createTop()


{
JPanel panel = new JPanel(new BorderLayout(10, 10));
JLabel label = new JLabel("Enter a name");
panel.add(label, BorderLayout.WEST);
panel.add(cmdAdd, BorderLayout.EAST);
panel.add(txtName);
return panel;
}

private JPanel createCenter()


{
lstNames = new JList(model);
JPanel panel = new JPanel(new BorderLayout());
panel.add(createLabel(), BorderLayout.NORTH);
panel.add(createLabel(), BorderLayout.SOUTH);
panel.add(new JScrollPane(lstNames));
return panel;
}

11
11
JAVA 2: PROGRAMS WITH A
GRAPHICAL
JAVA USER INTERFACE
2: PROGRAMS WITH A Hello Swing
GRAPHICAL USER INTERFACE Hello swIng

private JPanel createBottom()


{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(cmdClr);
return panel;
}

private void addListeners()


{
cmdAdd.addActionListener(new AddAction());
cmdClr.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
model.clear();
}
});
}

class AddAction implements ActionListener


{
public void actionPerformed(ActionEvent e)
{

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

12
12
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Hello Swing
GRAPHICAL USER INTERFACE Hello swIng

String name = txtName.getText().trim();


if (name.length() > 0)
{
model.addElement(name);
txtName.setText("");
txtName.requestFocus();
}
}
}
}

ItItlooks
looksundeniably
undeniablylike
likemuch
much(there
(thereare
are9797lines),
lines),and
andI Iwill
willexplain
explainbelow
belowwhat
whatititall
all
means. Of course one can not know that the code should be written as shown above,
means. Of course one can not know that the code should be written as shown above, but but
ififyou
youlook
lookthrough
throughthe
thecode,
code,you
youcan
canactually
actuallyeasily
easilyunderstand
understandthe
themeaning
meaningofofmost.
most.

There
Thereare
arethree
threeimport
importstatements,
statements,which
whichimports
importsthree
threepackages
packageswith
withclasses,
classes,two
twopackages
packages
from
from the AWT API and one package from the Swing API. These import statementswill
the AWT API and one package from the Swing API. These import statements willbe
be
part of any GUI program and in all the classes that define windows.
part of any GUI program and in all the classes that define windows.

The
Theclass
classisisnamed
namedMainWindow,
MainWindow,and andititinherits
inheritsthe
theclass
classJFrame.
JFrame.ItItisisaaSwing
Swingclass,
class,and
and
this is the class that defines all that is necessary to create a window and offers all the services
this is the class that defines all that is necessary to create a window and offers all the services
that
thatareareneeded
neededtotodefine
definehow
howthethewindow
windowshould
shouldbehave.
behave.

AAwindow
windowisisininprinciple
principlejust
justaasimply
simplyrectangular
rectangularareaareawithout
withoutany anycontent,
content,but butititmay
may
contain components. Each component is defined by a class, and in
contain components. Each component is defined by a class, and in this case the window this case the window
must
mustcontain
containan aninput
inputfield,
field,two
twobuttons
buttonsandandaalist
listbox.
box.They
Theyare
aredefined
definedasasinstance
instancevariables
variables
atatthe start of the class. An input field has the type JTextField, a button the
the start of the class. An input field has the type JTextField, a button the type JButton, type JButton,
and
andaalist
listbox
boxthethetype
typeJList.
JList.They
Theyare
areall
allSwing
Swingclasses.
classes.You
Youshould
shouldnote
notethat
thatthe
thelist
listbox
boxisis
not
notcreated,
created,when
whenthe thevariables
variablesare
aredefined,
defined,butbutthetheother
otherthree
threecomponents
componentsare. are.Finally,
Finally,aa
last
lastinstance
instancevariable
variableofofthe
thetype
typeDefaultListModel
DefaultListModelisisdefineddefinedandandisisexplained
explainedbelow.
below.

The
Theclass
classhas
hasaaconstructor
constructorthat
thatdoes
doesthe
thefollowing:
following:

--- defines
definesthe
thetext
textininthe
thetitle
titlebar
bar
--- defines
defines the window size, whichisisthe
the window size, which thesize
sizeofofthe
thewindow
windowhas haswhen
whenititopens
opens
--- defines
defines that the program should close when the user clicks the cross in thetitle
that the program should close when the user clicks the cross in the titlebar
bar
--- calls a method addListeners() that assigns functionality to the window’s
calls a method addListeners() that assigns functionality to the window’s buttons buttons
--- calls
callsaamethod
methodcreateWindow()
createWindow()placing
placingthethecomponents
componentsininthe thewindow
window
--- define that the window must be displayed on
define that the window must be displayed on the screen the screen

13
13
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Hello Swing

The class has a method called createLabel(), which creates an empty label. A label is a
component, and has the type JLabel, and it is a component that shows a text. In this
case it is a blank text, but the important thing is that it has a size which is defined with
setPreferredSize().

Components are placed in a window using a layout manager, which is an object that
determines the component’s size and position. A window (that is a JFrame) has by default
a BorderLayout. It is a layout manager that divides the window into 5 areas, and each area
may contain a component. The five areas are

1. NORTH, and it has always the same width as the window while the height is
determined by the height of the component
2. SOUTH, and it has always the same width as the window while the height is
determined by the height of the component
3. WEST, the height is the height of the window, except for what is used for NORTH
and SOUTH, while the width is determined by the width of the component
4. EAST, the height is the height of the window, except for what is used for NORTH
and SOUTH, while the width is determined by the width of the component
5. CENTER, that is the rest of the window

If an area is empty – there is not a component in the area – it fills nothing and is collapsed.
It is important to note that a BorderLayout can contain only 5 components.

If you now considers the method createWindow(), it starts using the method createLabel()
to place a component in each of the four areas NORTH, SOUTH, WEST and EAST.
The goal is to define a margin of 10 corresponding to the size of the components that are
created with the method createLabel(). Next, the method creates a new component of the
type JPanel. It is a component which in itself is not visible, but it has a layout manager (in
this case a BorderLayout) and can contain other components. The component is called panel,
and the last statement in the method createWindow() places the component CENTER in the
window. Before it is filled with content using three methods, called respectively createTop(),
createCenter() and createBottom().

14
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Hello Swing
GRAPHICAL USER INTERFACE Hello swIng

If
If II start
start with
with the
the last
last one,
one, that
that creates
creates aa JPanel
JPanel with
with aa FlowLayout
FlowLayout manager.
manager. It It isis aa layout
layout
manager,
manager, where components are flowing horizontally. In this case, I have indicated that the
where components are flowing horizontally. In this case, I have indicated that the
components must be aligned to the right edge. After the panel is created,
components must be aligned to the right edge. After the panel is created, I adds one of the I adds one of the
two
two buttons
buttons (the
(the one
one toto delete
delete the
the list
list box).
box). The
The result
result isis that
that you
you gets
gets aa button
button located
located inin
the lower right corner of the window, but because of the two layout
the lower right corner of the window, but because of the two layout managers properties, managers properties,
the
the component
component will will follow
follow thethe window’s
window’s bottom
bottom and
and right
right edge,
edge, when
when thethe window
window size size
isis changed.
changed.

The
The method
method createTop()
createTop() creates
creates aa component
component to to the
the top,
top, aa JPanel
JPanel with
with aa label
label on
on the
the left,
left,
aa button on the right and an input box in the center. The three components
button on the right and an input box in the center. The three components are placed are placed
by
by aa BorderLayout,
BorderLayout, where where the
the input
input field
field txtName
txtName isis placed
placed CENTER.
CENTER. As As aa CENTER
CENTER area area
always fills it all, is the result of the layout, that the input field will always fill
always fills it all, is the result of the layout, that the input field will always fill the part the part
of
of the
the panel,
panel, which
which isis not
not used
used by by the
the other
other two
two components
components and and thereby
thereby adjust
adjust to to the
the
window width. You should note that the panel is created as follows:

360°
window width. You should note that the panel is created as follows:

.
JPanel panel = new JPanel(new BorderLayout(10, 10));

Here
Here you
space
you specify
specify by
should be
by the
the parameters
between
parameters for
the
for the
the BorderLayout
components.
space should be between the components.
BorderLayout class’s thinking
class’s constructor,
constructor, how
how much
much free
free

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


15
15
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Hello
HelloSwing
swIng

The
Themethod
methodcreateCenter()
createCenter()creates
createsthe
thelist
listbox.
box.When
Whenyou youdodothat
thatyou
youassign
assignthe
thelist
listbox
boxtoto
a adata
datamodel
model––ananobject
objectofofthe
thetype
typeDefaultListModel
DefaultListModel––which whichmust
mustcontain
containthethedata
datathat
that
the
thelist
listbox
boxshould
shoulddisplay.
display.The
Themethod
methodcreates
createsa aJPanel
JPanelwith
witha aBorderLayout,
BorderLayout,and andassigns
assigns
ananempty label NORTH and SOUTH to get some space, respectively
empty label NORTH and SOUTH to get some space, respectively at top and bottom. at top and bottom.
When
Whenthe thelist
listbox
boxisisplaced
placedininthe
thepanel,
panel,ititisisencapsulated
encapsulatedinina aJScrollPane,
JScrollPane,which
whichallows
allows
that
thatyou
youcan
canscroll
scrollthe
thecontent.
content.

All
Allthe
theforegoing
foregoingconcerning
concerningonlyonlyhow
howtotocreate
createand
anddesign
designthe thewindow.
window.You Youshould
shouldnote note
that
thatititisisa astable
stabledesign
designininthe
thesense
sensethat
thatthe
thecomponents
componentsfollowsfollowsthethewindow
windowsize. size.What
What
remains
remainsisistotoattach
attachfunctionality
functionalitytotothe
thetwo
twobuttons.
buttons.When
Whenthe theuser
userclicks
clicksa abutton,
button,ititraises
raises
ananevent.
event.Specifically,
Specifically,this
thismeans
meansthat
thatother
otherobjects
objectscan
canregister
registerasaslisteners
listenersforforthis
thisevent
eventbyby
specifying a method with a specific signature. This method is called an event
specifying a method with a specific signature. This method is called an event handler. When handler. When
the
thebutton
buttonisisclicked,
clicked,ititwill
willcheck
checkwhether
whetherthere
thereare
arelisteners,
listeners,andandififso,
so,will
willititcall
callthese
these
listeners.
listeners.ThisThissends
sendsmessages
messagestotothethelistener
listenerobjects
objectsthat
thattells
tellsthat
thatthe
thebutton
buttonisisclicked,
clicked,
and
andthethelisteners
listenerscan
candodosomething.
something.

Above,
Above,therethereisisananinner
innerdefined
definedclass,
class,which
whichisissimply
simplya aclass
classwithin
withinanother
anotherclass.
class.It’s
It’s
called
calledAddAction
AddActionand andimplements
implementsananinterface
interfacecalled
calledActionListener.
ActionListener.ThisThisinterface
interfacedefines
defines
only
onlya asingle
singlemethod
methodcalled calledactionPerformed()
actionPerformed()and andisisananexample
exampleofofananevent
eventhandler.
handler.ItIt
should
shouldbebelinked
linkedtotothe theAddAddbutton,
button,asashappens
happenswidthwidththethemethod
methodaddActionListener().
addActionListener().
The
Theevent
eventhandler
handlerretrieves
retrievesthethetext
textfrom
fromthe theinput
inputfield,
field,and
andififthe
thetext
textisisnot
notempty,
empty,thethe
handler
handlerupdates
updatesthethemodel
modelofofthethelist
listboxboxwith
withthethetext,
text,and
andthe
theresult
resultisisthat
thatthe
theentered
entered
name
nameappears
appearsininthethelist
listbox.
box.Next,
Next,the thecontent
contentofofthetheinput
inputfield
fieldisisdeleted,
deleted,andandfinally
finally
the
the field is given focus, and the input field is ready to enter the next name. That theclass
field is given focus, and the input field is ready to enter the next name. That the class
AddAction
AddActionimplements
implementsthe theinterface
interfaceActionListener
ActionListenermeansmeansthat
thatananobject
objectofoftype
typeAddAction
AddAction
can
canbebeused
usedasasa alistener
listenerobject
objectofofa abutton.
button.ItIthappens
happensininthethemethod
methodaddListeners()
addListeners()with
with
the
thefollowing
followingstatement:
statement:

cmdAdd.addActionListener(new AddAction());

cmdAdd
cmdAddisisthethename
nameofofthe
thebutton,
button,and
andthe theclass
classJButton
JButton(which
(whichare
areofofthe
thebutton’s
button’stype)
type)
have
havea amethod
methodaddActionListener(),
addActionListener(),which
whichcan canregister
registera alistener
listenerobject.
object.TheTheresult
resultisisthat
that
when
whenyouyouclick
clickthe
theAdd
Addbutton,
button,then
thenlistener
listenerobject’s
object’sactionPerformed()
actionPerformed()method
methodexecutes.
executes.You
You
should
shouldnote
notethat
thatthis
thismethod
methodcan
canrefer
refertotothe
theinstance
instancevariables
variablesininthe
theclass
classMainWindow.
MainWindow.
This is possible because AddAction is an inner
This is possible because AddAction is an inner class.class.

There
Theremust
mustnow nowbebedone
donethethesame
samefor
forthe
thesecond
secondbutton,
button,butbutthis
thistime
timethe
theevent
eventhandler
handler
isisvery
verysimple,
simple,since
sinceititalone
alonemust
mustdelete
deletethe
thecontents
contentsofofthe
themodel
modelforforthe
thelist
listbox.
box.I Ihave
have
therefore instead of writing a new listener class added a listener object created on the
therefore instead of writing a new listener class added a listener object created on the basis basis
ofofanananonymous
anonymousclass:class:

1616
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Hello Swing
GRAPHICAL USER INTERFACE Hello swIng
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Hello swIng

cmdClr.addActionListener(new ActionListener()
{
cmdClr.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent e)
{
public void actionPerformed(ActionEvent e)
{ model.clear();
} model.clear();
});
}
});
At this point you just need to accept the syntax, but cmdClear is the name of a button, and
At this point you just need to accept the syntax, but cmdClear is the name of a button, and
IAtuse
thisitspoint
addActionListener()
you just need totoaccept
associate a listener
the syntax, butobject.
cmdClearThat is, as
is the explained
name above,and
of a button, an
I use its addActionListener() to associate a listener object. That is, as explained above, an
object that
I use its implements the interface
addActionListener() ActionListener,
to associate and such
a listener object. an is,
That object can be instantiated
as explained above, an
object that implements the interface ActionListener, and such an object can be instantiated
on the that
object basisimplements
of an anonymous class ActionListener,
the interface with a syntax, and as shown
such an above.
objectOne
can can discuss the
be instantiated
on the basis of an anonymous class with a syntax, as shown above. One can discuss the
pros
on theandbasis
consofwith respect to anonymous
an anonymous class with classes,
a syntax, since they can
as shown be difficult
above. One can to understand
discuss the
pros and cons with respect to anonymous classes, since they can be difficult to understand
and
pros read, but are
and cons withthey very to
respect simple classes –classes,
anonymous as in this
sincecase
they– can
it can
be be quite to
difficult excellent.
understand
and read, but are they very simple classes – as in this case – it can be quite excellent.
and read, but are they very simple classes – as in this case – it can be quite excellent.
Now the window is finished, but this is not in itself a program. There must be instantiated
Now the window is finished, but this is not in itself a program. There must be instantiated
an
Nowobject whose type
the window is MainWindow,
is finished, but this isand
not itinshould
itself abe in the main
program. Thereprogram:
must be instantiated
an object whose type is MainWindow, and it should be in the main program:
an object whose type is MainWindow, and it should be in the main program:
package helloswing;
package helloswing;
public class HelloSwing
{
public class HelloSwing
{ public static void main(String[] args)
{
public static void main(String[] args)
{ new MainWindow();
} new MainWindow();
}}
}
Then the program is finished and can be run. As already mentioned, much is being written,
Then
Thenthe
theprogram
although it isisfinished
is a very
program simple and
andcan
canbebe
finishedprogram, butrun.
theAs
run. already
example
As mentioned,
mentioned,much
alreadyexaggerating, partlyisis
much being
beingwritten,
because it is the
written,
although
same to ithappen
although itisisa avery
every
very simple
time,program,
simple but
butthe
and secondly,
program, example
parts
the of theexaggerating,
example code can bepartly
exaggerating, partlybecause
written ititisisthe
simpler.
because the
same
sametotohappen
happenevery everytime,
time,and
andsecondly,
secondly,parts
partsofofthe
thecode
codecan
canbebewritten
writtensimpler.
simpler.
EXERCISE 1
EXERCISE
EXERCISE 1
In this exercise1you have to make some changes and improvements to the program HelloSwing.
InStart
Inthis
thisexercise
by you
youhave
creating
exercise ahave totomake
copy makesome
and somechanges
open itchanges and
andimprovements
in NetBeans. totothe
In MainWindow
improvements theprogram HelloSwing.
is a method
program called
HelloSwing.
Start
Startby bycreating
createLabel(), a acopy
which
creating and
is used
copy andtoopen
add itaitin
open inNetBeans.
margin outsideInIn
NetBeans. MainWindow
the isisa amethod
window’s content
MainWindow and tocalled
method create
called
createLabel(),
space between
createLabel(), which
which isisused
usedtotoadd
the components. This
add a amargin
can outside
be done
margin in the
outside thewindow’s
other way. Remove
window’s contentthisand
content totocreate
method.
and You
create
space
get
space6between
between the
statements components.
the(which refers This
components. to can
this
This bebedone
method),
can ininother
donewhere way.
way.Remove
NetBeans
other reports
Remove this
anmethod.
this You
error. Delete
method. You
get 6
these statements
get 6 6statements (which
statements. refers
If yourefers
(which to
then to this
runthis method),
themethod), where
program,where NetBeans
the result reports
is the reports
NetBeans an
following: error. Delete
an error. Delete
these
these66statements.
statements.IfIfyou youthen
thenrunrunthetheprogram,
program,thetheresult
resultisisthe
thefollowing:
following:

17
17
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Hello
Hello Swing
swIng

To
To define
define margins
margins you
you need
need to
to add
add an
an import
import statement:
statement:

import javax.swing.border.*;

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

18
18
JAVA
JAVA2: PROGRAMS WITH AA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
GRAPHICAL
GRAPHICAL USER
USERINTERFACE
INTERFACE Hello
HelloSwing
GRAPHICAL USER INTERFACE Hello swIng
swIng

The
Themethod
The methodcreateWindow()
method createWindow()must
createWindow() mustthen
must thenbe
then bechanged
be changedtoto
changed tothe
thefollowing:
the following:
following:

private
private void
void createWindow()
createWindow()
{
{
JPanel
JPanel panel
panel == new
new JPanel(new BorderLayout(0, 10));
JPanel(new BorderLayout(0, 10));
panel.setBorder(new EmptyBorder(10,
panel.setBorder(new EmptyBorder(10, 10,
10, 10,
10, 10));
10));
panel.add(createTop(),
panel.add(createTop(), BorderLayout.NORTH);
BorderLayout.NORTH);
panel.add(createBottom(), BorderLayout.SOUTH);
panel.add(createBottom(), BorderLayout.SOUTH);
panel.add(createCenter());
panel.add(createCenter());
add(panel);
add(panel);
}
}

So
Sowould
So woulditit
would itall
alllook
all lookright
look rightagain.
right again.
again.

You
Youmust
You mustthen
must thenadd
then addaaanew
add newbutton
new buttontoto
button tothe
thebottom
the bottomofof
bottom ofthe
thewindow:
the window:
window:

You
Youdo
You dothis
do thisasas
this asfollows:
follows:
follows:

1.
1.create
1. createaaanew
create newinstance
new instancevariable
instance variabletoto
variable toaaabutton
buttonthat
button thatyou
that youcan
you cancall
can callcmdCount
call cmdCount
cmdCount
2.
2. add the button (a component) to the window in the methodcreateBottom()
2. add
add the
the button
button (a
(acomponent)
component) to
tothe
thewindow
window in
inthe
the method
method createBottom()
createBottom()

Now
Nowthe
Now thewindow
the windowshould
window shouldhave
should haveanother
have anotherbutton.
another button.The
button. Thetwo
The twobuttons
two buttonsatat
buttons atthe
thebottom
the bottomisis
bottom isprobably
probably
probably
not
not equal in size, but because they are laid out with a FlowLayout, you can define theirsize
not equal
equalin
insize,
size,but
butbecause
because they
theyare
arelaid
laidout
outwith
witha aFlowLayout,
FlowLayout, you
you can
candefine
define their
their size
size
(in
(increateBottom())
createBottom()) as
asfollows:
follows:
(in createBottom()) as follows:

cmdAnt.setPreferredSize(new
cmdAnt.setPreferredSize(new Dimension(80,
Dimension(80, 27));
27));

Assign
Assignthe
Assign theClear
the Clearbutton
Clear buttonthe
button thesame
the samesize.
same size.
size.

1919
19
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Hello Swing
GRAPHICAL USER INTERFACE Hello swIng

What remains is to attach an action for the new button. When the button is clicked, the
What remains is to attach an action for the new button. When the button is clicked, the
program must open the following message box that shows how many names are entered:
program must open the following message box that shows how many names are entered:

Start by adding another inner class that defines a listener object:


Start by adding another inner class that defines a listener object:

class CountAction implements ActionListener


{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(MainWindow.this, "You have entered " +
model.getSize() + " names", "Message", JOptionPane.INFORMATION_MESSAGE);
}
}

Here
Here isis showMessageDialog()
showMessageDialog() aa static
static method
method in in the
the class
class JOptionPane,
JOptionPane, which
which opens
opens aa message
message
box.
box. It has four parameters, wherein only the first two are required. The first tells who owns
It has four parameters, wherein only the first two are required. The first tells who owns
the
the message box, and the next is the text to be displayed. The third is the text in the title
message box, and the next is the text to be displayed. The third is the text in the title
bar, while the remaining is telling the icon the message box will
bar, while the remaining is telling the icon the message box will display. display.

After
After you
you have
have defined
defined this
this class,
class, you
you only
only need
need in
in the
the method
method addListeners()
addListeners() to
to make
make your
your
application to listener for events from the button.
application to listener for events from the button.

You
You must
must add
add one
one last
last change
change to
to the
the program.
program. The
The Clear
Clear button
button deletes
deletes the
the content
content of
of the
the
list box, but without a warning, which in practice can be unlucky. It would be better
list box, but without a warning, which in practice can be unlucky. It would be better with with
aa warning:
warning:

20
20
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Hello Swing
GRAPHICAL USER INTERFACE Hello swIng

To add that, you must change the event handler for the Clear button so that its code is
To add that, you must change the event handler for the Clear button so that its code is
as follows:
as follows:

if (JOptionPane.showConfirmDialog(MainWindow.this,
"Are you sure you want to delete the list?", "Warning",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
== JOptionPane.YES_OPTION) model.clear();

AXA Global
Graduate Program
Find out more and apply

21
21
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHAA
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE HelloSwing
Hello swIng

EXERCISE22
EXERCISE
Createaanew
Create newNetBeans
NetBeansproject,
project,that
thatyou
youcan
cancall
callCalculator.
Calculator.You
Youshould
shouldwrite
writeaaprogram
program
thatopens
that opensaawindow,
window,asasshown
shownbelow:
below:

Thewindow
The windowhas hastwo
twoinput
inputfields
fieldswhere
whereyou youmust
mustenter
enternumbers.
numbers.Furthermore,
Furthermore,therethereare
are
fourbuttons
four buttons––oneonefor
foreach
eachofofthethefour
fourarithmetical
arithmeticaloperations.
operations.When
Whenyou youclick
clickaabutton,
button,
theprogram
the programshould
shouldinsert
insertaaline
lineininthe
thelist
listbox,
box,which
whichshows
showsthe
theresults
resultsofofthat
thatcalculation.
calculation.
IfIfthere
thereisisan
anerror,
error,the
theprogram
programsimplysimplyinserts
insertsan
anerror
errormessage.
message.The
TheClear
Clearbutton
buttonshould
should
workininthe
work thesame
samewaywayasasininthe
thefirst
firstprogram.
program.

Whenthe
When thewindow
windowsize
sizeisischanged,
changed,all
allbuttons
buttonsmust
mustfollow
followthe
thewindow’s
window’sright
rightedge,
edge,while
while
thetwo
the twoinput
inputboxes
boxeswill
willuse
usethe
theremaining
remainingspace
spaceequally.
equally.

ItItisisclear
clearthat
thatthe
theprogram
programisissimilar
similartotothe
theHelloSwing,
HelloSwing,but
butI Iwould
wouldsuggest
suggestthat
thatyou
youstart
start
fromscratch
from scratchand
andfollow
followthe
theguidelines
guidelinesbelow.
below.You
Youcan
canofofcourse
courseuse
useHelloSwing
HelloSwingtotosee
seehow
how
theindividual
the individualstatements
statementsshould
shouldbe
bewritten.
written.

1)1)Add
Addaanew
newclass
classnamed
namedMainWindow
MainWindowtotothe
theproject.
project.Start
Startby
bytyping
typingthe
thefollowing
followingcode:
code:

package calculator;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MainWindow extends JFrame


{
public MainWindow()
{

2222
JAVA
JAVA2:2:
JAVA PROGRAMS
2: PROGRAMS
PROGRAMS WITH
WITH
WITHAA
A
GRAPHICAL
GRAPHICAL
GRAPHICAL USER
USER
USERINTERFACE
INTERFACE
INTERFACE Hello
Hello
HelloSwing
swIng
swIng

setTitle("Calculator");
setTitle("Calculator");
setSize(500, 300);
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setVisible(true);
}}
}}

You must
You must then
then edit
edit the
the main
main class
class to
to open
open the
the window:
window:

package calculator;
package calculator;

public class
public class RegneMaskine
RegneMaskine
{{
public static
public static void
void main(String[]
main(String[] args)
args)
{{
new MainWindow();
new MainWindow();
}}
}}

Test
Testthe
Test theprogram.
the program.This
program. Thisshould
This shouldopen
should openaaawindow,
open window,and
window, anditititisisisinin
and inaaaway
wayaaaminimal
way minimalGUI
minimal GUIprogram,
GUI program,
program,
but
butnevertheless
but neverthelessaaaprogram
nevertheless programwith
program withaaawindow
with windowwith
window withaaatitle
with titlebar
title barthat
bar thatcan
that canbe
can bemoved
be movedaround
moved aroundon
around on
on
the
thescreen
the screenand
screen andresized.
and resized.
resized.

2)2)
2)Add
Addinstance
Add instancevariables
instance variablestoto
variables tothe
theprogram.
the program.There
program. Thereisisisaaaneed
There needfor
need for999variables:
for variables:
variables:

---- twotwoinput
two inputfields
input fieldsthat
fields thatyou
that youshould
you shouldcall
should calltxtNum1
call txtNum1and
txtNum1 andtxtNum2
and txtNum2
txtNum2
---- five
fivebuttons
five buttonswith
buttons withthe
with thenames
the namescmdAdd,
names cmdAdd,cmdSub,
cmdAdd, cmdSub,cmdMul,
cmdSub, cmdMul,cmdDiv
cmdMul, cmdDivand
cmdDiv andcmdClr
and cmdClr
cmdClr
---- aaalist
listbox
list boxwith
box withthe
with thename
the namelstRes
name lstRes(you
lstRes (youmust
(you mustnot
must notcreate
not createan
create anobject,
an object,but
object, butjust
but justdefine
just define
define
aaavariable)
variable)
variable)
---- aaamodel
modelfor
model forthe
for thelist
the listbox,
list box,and
box, andthe
and thename
the namemust
name mustbe
must bemodel
be model
model

Compile
Compilethe
Compile theprogram
the programand
program andrun
and runit.it.
run it.There
Thereare
There areno
are novisible
no visibledifferences,
visible differences,and
differences, andthis
and thisisisisjust
this justtoto
just toensure
ensure
ensure
that
thatyou
that youdo
you donot
do nothave
not haveany
have anysyntax
any syntaxerrors.
syntax errors.
errors.

3)3)
3)YouYoumust
You mustnext
must nextadd
next addaaamethod
add methodnamed
method namedcreateCenter().
named createCenter().It’s
createCenter(). It’sbasically
It’s basicallythe
basically thesame
the samemethod
same methodasas
method asinin
in
exercise
exercise1,1,
exercise 1,and
andthe
and thetask
the taskisisistoto
task tocreate
createthe
create thelist
the listbox
list boxand
box andplace
and placeitititinin
place inaaaJScollPane.
JScollPane.The
JScollPane. Theonly
The onlydifference
only difference
difference
isisisthat
thatthe
that thelist
the listbox
list boxisisisnow
box nowcalled
now calledsomething
called somethingelse.
something else.Next,
else. Next,add
Next, addthe
add themethod
the methodcreateWindow(),
method createWindow(),
createWindow(),
which
whichcreates
which createsthe
creates thewindow’s
the window’scomponents:
window’s components:
components:

private void
private void createWindow()
createWindow()
{{
JPanel panel
JPanel panel == new
new JPanel(new
JPanel(new BorderLayout(0,
BorderLayout(0, 10));
10));
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.add(createCenter());
panel.add(createCenter());
add(panel);
add(panel);
}}

2323
23
JAVA 2:
JAVA
JAVA 2: PROGRAMS
2: PROGRAMS WITH
PROGRAMS WITH A
WITH A
A
GRAPHICAL USER
GRAPHICAL
GRAPHICAL USER INTERFACE
USER INTERFACE
INTERFACE Hello Swing
Hello
Hello swIng
swIng

Keep in
Keep
Keep in mind
in mind that
mind that ititit isisis necessary
that necessary to
necessary to add
to add an
add an import
an import statement
import statement
statement

import javax.swing.border.*;
import javax.swing.border.*;

You should
You
You should also
should also call
also call the
call the method
the method createWindow()
method createWindow() from
createWindow() from the
from the constructor.
the constructor. Run
constructor. Run the
Run the program,
the program,
program,
the result
the
the result should
result should now
should now be
now be that
be that you
that you get
you get aaa window
get window with
window with aaa list
with list box.
list box.
box.

4) Add
4)
4) Add aaa method
Add method createBottom().
method createBottom(). It
createBottom(). It must
It must be
must be the
be the same
the same method
same method as
method as in
as in the
in the program
the program HelloSwing
program HelloSwing
HelloSwing
whichadds
which
which addsthe
adds theClear
the Clearbutton
Clear buttonto
button tothe
to thewindow.
the window.You
window. Youmust
You mustthen
must thenadd
then addaaastatement
add statementto
statement tocreateWindow(),
to createWindow(),
createWindow(),
so the
so
so the panel
the panel that
panel that createBottom()
that createBottom() creates
createBottom() creates are
creates are added
are added to
added to the
to the bottom
the bottom of
bottom of the
of the window:
the window:
window:

private void
private void createWindow()
createWindow()
{{
JPanel panel
JPanel panel == new
new JPanel(new
JPanel(new BorderLayout(0,
BorderLayout(0, 10));
10));
panel.setBorder(new EmptyBorder(10,
panel.setBorder(new EmptyBorder(10, 10,
10, 10,
10, 10));
10));
panel.add(createBottom(), BorderLayout.SOUTH);
panel.add(createBottom(), BorderLayout.SOUTH);
panel.add(createCenter());
panel.add(createCenter());
add(panel);
add(panel);
}}

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

24
24
24
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Hello Swing
GRAPHICAL USER INTERFACE Hello swIng

If you then run the program, the result should be the following:
If you then run the program, the result should be the following:

5) You now need to write the code to the top panel, which is a little more difficult. Start
5) You now need to write the code to the top panel, which is a little more difficult. Start
by adding the following method:
by adding the following method:

private void initButton(JButton cmd)


{
cmd.setPreferredSize(new Dimension(29, 29));
cmd.setFont(new Font("Liberation Sherif", Font.PLAIN, 16));
cmd.setMargin(new Insets(0, 0, 0, 0));
}

ItIthas
hasaabutton
buttonasasaaparameter,
parameter,and
andassign
assignthe
thebutton
buttonaasize
sizeofof29
29××29,
29,defines
definesthe
thefont,
font,
the button should apply and remove an internal margin, as a button has by default.
the button should apply and remove an internal margin, as a button has by default.

You
Youcan
canthen
thenadd
addthe
thefollowing
followingmethod:
method:

private JPanel createRight()


{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
initButton(cmdAdd);
initButton(cmdSub);
initButton(cmdMul);
initButton(cmdDiv);
panel.add(cmdAdd);
panel.add(cmdSub);
panel.add(cmdMul);
panel.add(cmdDiv);
return panel;
}

25
25
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Hello Swing
GRAPHICAL
JAVA USER INTERFACE
2: PROGRAMS WITH A Hello swIng
GRAPHICAL USER INTERFACE Hello swIng

The
Themethod
methodcalls
callsinitButton()
initButton()for
foreach
eachofofthe
thefour
fourcalculation
calculationbuttons,
buttons,and
andthen
thenplaces
placesthe
the
four
The buttons
method in a
calls JPanel with
initButton()FlowLayout.
for each
four buttons in a JPanel with FlowLayout. of the four calculation buttons, and then places the
four buttons in a JPanel with FlowLayout.
As
Asthe
thenext
nextstep
stepyouyouneed
needtotocreate
createaapanel
paneltotothe
thetwo
twoinput
inputfields:
fields:
As the next step you need to create a panel to the two input fields:
private JPanel createLeft()
private
{ JPanel createLeft()
{ JPanel panel = new JPanel(new GridLayout(1, 2, 10, 0));
JPanel panel = new JPanel(new GridLayout(1, 2, 10, 0));
panel.add(txtNum1);
panel.add(txtNum1);
panel.add(txtNum2);
panel.add(txtNum2);
return panel;
} return panel;
}

HereI Iuse
Here useaaGridLayout.
GridLayout.ItItisisaalayout
layoutmanager
managerthat thatdivides
dividesaapanel
panelininaanumber
numberofofrowsrows
Here I
andcolumns.use a
columns.This GridLayout.
Thisdivides It is
dividesaapanela layout manager
panelininaanumber that
numberofofcells divides
cellsthat
thatall a panel
allhave in
havethe a
thesame number
samesize. of rows
size.InInthis
this
and
and columns.
case,there
thereisisone Thisrow
one divides a panel in a and
number of cells that the
all have the same of
size.
twoIn this
case, row ofoftwo
two columns,
columns, and thetheresult
resultisisthat
that panelconsists
the panel consists of two cells,
cells,
case,
whichthere isalways
one row
willalways beofof two
ofthe columns,
thesame size.and
samesize. Thethetwo result
inputis that
fieldsthearepanel
addedconsists
theof two cells,
which will be The two input fields are added totothe panel,
panel, and
and
which
eachfield will
fieldwillalways be of
willautomatically the
automaticallyfillsame
fillthe size.
thecell The
cellthat two input
thatititisislocated
locatedin. fields
in.The are added
Theconstructor to
constructorfor the panel,
forGridLayout and
GridLayout
each
each field
objecthas will
hastwo automatically
twoadditional fill
additionalparameters the
parametersthatcell that it
thatindicates is located
indicateshow howmuch in. The
muchspace constructor
spacethere
thereshouldfor
shouldbe GridLayout
bebetween
between
object
object
thecells hashorizontally
cells two additional parameters
vertically. that indicates how much space there should be between
andvertically.
the horizontally and
the cells horizontally and vertically.
Finally,add
Finally, addthe
thefollowing
followingmethod:
method:
Finally, add the following method:
private JPanel createTop()
private
{ JPanel createTop()
{ JPanel panel = new JPanel(new BorderLayout(10, 10));
JPanel panel = new JPanel(new
panel.add(createRight(), BorderLayout(10, 10));
BorderLayout.EAST);
panel.add(createRight(),
panel.add(createLeft()); BorderLayout.EAST);
panel.add(createLeft());
return panel;
} return panel;
}

It returns a panel with a BorderLayout. For this panel is added the panel with the 4 calculation
ItIt returnsso
returns
buttons aapanel
panel with
it sitswith aaBorderLayout.
to the BorderLayout. Forpanel
For
right, and the thispanel
this panel isadded
withistheadded
twothethe panel
panel
input with
with
fields the
sothe 44calculation
that calculation
it uses the
buttons
buttons so it sits to the right, and the panel with the two input fields
remaining space. If you then apply the method createTop() in createWindow(), youuses
so it sits to the right, and the panel with the two input fields so
so that
that it
it uses the
can the
add
remaining
remaining space.
space.
the top panel andIfIfyou
youdesign
the thenapply
then apply the
the
of the method
method
window createTop()
iscreateTop()
now inincreateWindow(),
finished. createWindow(),you youcan
canadd
add
thetop
the toppanel
paneland andthe thedesign
designofofthe
thewindow
windowisisnow nowfinished.
finished.

26
26
JAVA 2:
JAVA 2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL USER
GRAPHICAL USER INTERFACE
INTERFACE Hello Swing
Hello swIng

6) What
6) What remains is
remains is to
to attach
attach event
event handlers
handlers to
to the
the 5
5 buttons.
buttons. Start
Start by
by adding
adding the
the
following
following method:
method:

private void calculate(char ch)


{
try
{
double tal1 = Double.parseDouble(txtTal1.getText());
double tal2 = Double.parseDouble(txtTal2.getText());
double res = 0;
switch (ch)
{
case '+': res = tal1 + tal2; break;
case '-': res = tal1 – tal2; break;
case '*': res = tal1 * tal2; break;
case '/': res = tal1 / tal2; break;
}
model.addElement(String.format("%f %s %f = %f", tal1, "" + ch, tal2, res));
}
catch (Exception ex)
{
model.addElement(ex.toString());
}

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

27
27
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Hello
HelloSwing
swIng

txtTal1.setText("");
txtTal2.setText("");
txtTal1.requestFocus();
}

ItIthas
hasaaparameter
parameterthat
thattells
tellswhich
whichcalculation
calculationtotobe
becarried
carriedout.
out.The
Themethod
methodperforms
performsthe
the
calculation and inserts a line in the model for the list box.
calculation and inserts a line in the model for the list box.

This
Thismethod
methodmustmustbe becalled
calledfrom
fromthethebuttons
buttonsevent
eventhandlers.
handlers.This
Thisshould
shouldbebedone
doneby
bythe
the
same way as in the program HelloSwing to add a method addListeners(), which
same way as in the program HelloSwing to add a method addListeners(), which adds eventadds event
handlers
handlersfor
forthe
thebuttons,
buttons,but
butthis
thistime
timefor
forall
all55buttons,
buttons,with
withthe
thehelp
helpofofanonymous
anonymousclasses.
classes.
Remember to call the methods addListeners() from the constructor in MainWndow.
Remember to call the methods addListeners() from the constructor in MainWndow.

Then
Thenthe
theprogram
programshould
shouldbe
befinished
finishedand
andcould
couldbe
betested.
tested.

28
28
JAVA 2: 2:
JAVA PROGRAMS
PROGRAMS WITH AA
WITH
GRAPHICAL
GRAPHICAL USER
USERINTERFACE
INTERFACE Fonts
Fontsand
andcolors
Colors

3
3 FONTS
FONTSAND
ANDCOLORS
COLORS
Most
Mostofofthethecomponents
componentsthatthatcan
canbebeinserted
insertedinto
intoa awindow/panel
window/paneldisplays
displaystext
textand
andyouyou
can
candefine
definethethefont,
font,which
whichthey
theymust
mustuse.use.Similarly,
Similarly,you
youcan
candefine
definethe
thecolor
colorofofthe
thetext
text
uses,
uses,and
andfinally
finallyyou
youcan
candefine
definethethebackground
backgroundcolor.
color.The
Theprogram
programTextColor
TextColoropens
opensthe the
following
followingwindow:
window:

It Itis isa avery


verysimple
simpleprogram
programthat
thatininfact
factdodonothing.
nothing.It Ithas
hasthe
thesame
samearchitecture
architectureasasthe the
previous
previousprograms,
programs,ininwhich
whichthe
themain
mainclass
classopens
opensa awindow,
window,which
whichininthis
thiscase
caseis isdefined
defined
asasfollows:
follows:

package textcolor;

import java.awt.*;
import javax.swing.*;

public class MainWindow extends JFrame


{
public MainWindow()
{
setTitle("Font og farver");
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
createWindow();
setVisible(true);
}

private void createWindow()


{
add(createLabel("North", Color.blue, Color.white,
new Font("Liberation Serif", Font.PLAIN, 24), 0, 30),
BorderLayout.NORTH);

29 29
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Fonts and colors
GRAPHICAL USER INTERFACE Fonts and Colors

add(createLabel("South", Color.green, Color.black,


new Font("Liberation Serif", Font.BOLD, 36), 0, 50),
BorderLayout.SOUTH);
add(createLabel("West", Color.magenta, Color.black,
new Font("Liberation Serif", Font.ITALIC, 18), 60, 0),
BorderLayout.WEST);
add(createLabel("East", Color.red, Color.white,
new Font("Liberation Serif", Font.BOLD | Font.ITALIC, 24), 60, 0),
BorderLayout.EAST);
add(createLabel("Center", new Color(240, 240, 240), Color.pink,
new Font("Liberation Serif", Font.BOLD, 96), 0, 0));
}

private JLabel createLabel(String text, Color bg, Color fg, Font font,
int width, int height)
{
JLabel label = new JLabel(text);
label.setOpaque(true);
label.setBackground(bg);
label.setForeground(fg);
label.setFont(font);
label.setHorizontalAlignment(JLabel.CENTER);
label.setPreferredSize(new Dimension(width, height));

30
30
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Fonts
Fontsand
andcolors
Colors

return label;
}
}

I’ll start with the method createLabel(), which creates and returns a component of the type
I’ll start with the method createLabel(), which creates and returns a component of the type
JLabel. It is a component that shows a text. The method has 6 parameters:
JLabel. It is a component that shows a text. The method has 6 parameters:

-- The first is the text.


- The first is the text.
-- The next is the background color, which is an object of the type Color.
- The next is the background color, which is an object of the type Color.
-- The third is the foreground color and thus the text color. It is likewise an object
- The third is the foreground color and thus the text color. It is likewise an object
of type Color.
of type Color.
-- The fourth parameter is the font, which is an object of type Font.
- The fourth parameter is the font, which is an object of type Font.
-- The last two parameters are respectively the width and height og the component.
- The last two parameters are respectively the width and height og the component.

The method’s statements are easy enough to figure out, but you must again note how to
The method’s statements are easy enough to figure out, but you must again note how to
define the size of a component with setPreferredSize(). A JLabel is shown with transparent
define the size of a component with setPreferredSize(). A JLabel is shown with transparent
background by default, and therefore can not have a background color unless you say that
background by default, and therefore can not have a background color unless you say that
the background should not be transparent. This is done with setOpaQue().
the background should not be transparent. This is done with setOpaQue().

A frame window is by default born with a BorderLayout, and you can immediately add 5
A frame window is by default born with a BorderLayout, and you can immediately add 5
components, as happens in the method createWindow().
components, as happens in the method createWindow().

A BorderLayout divides as mentioned a window/ panel in 5 areas, called respectively NORTH,


A BorderLayout divides as mentioned a window/ panel in 5 areas, called respectively NORTH,
EAST, SOUTH, WEST and CENTER, with the latter as default. Each region may contain
EAST, SOUTH, WEST and CENTER, with the latter as default. Each region may contain
a single component, but may also be empty. If so, the area fills nothing on the screen. If
a single component, but may also be empty. If so, the area fills nothing on the screen. If
an area contains a component, the following applies concerning the size:
an area contains a component, the following applies concerning the size:

-- NORTH: The width is the width of the panel, and the height is determined by
- NORTH: The width is the width of the panel, and the height is determined by
the component’s height defined by its preferred size. The width of the component
the component’s height defined by its preferred size. The width of the component
in terms of its preferred size is ignored.
in terms of its preferred size is ignored.
-- SOUTH: The width is the width of the panel, and the height is determined by the
- SOUTH: The width is the width of the panel, and the height is determined by the
component’s height defined by its preferred size. The width of the component in
component’s height defined by its preferred size. The width of the component in
terms of its preferred size is ignored.
terms of its preferred size is ignored.
-- WEST: The height is the height of the panel minus the height that is used to NORTH
- WEST: The height is the height of the panel minus the height that is used to NORTH
and SOUTH, and the width is determined by the component’s width defined by
and SOUTH, and the width is determined by the component’s width defined by
its preferred size. The component’s height in terms of its preferred size is ignored.
its preferred size. The component’s height in terms of its preferred size is ignored.
-- EAST: The height is the height of the panel minus the height that is used to NORTH
- EAST: The height is the height of the panel minus the height that is used to NORTH
and SOUTH, and the width is determined by the component’s width defined by
and SOUTH, and the width is determined by the component’s width defined by
its preferred size. The component’s height in terms of its preferred size is ignored.
its preferred size. The component’s height in terms of its preferred size is ignored.
-- CENTER: The width is the width of the panel minus the width used by the WEST
- CENTER: The width is the width of the panel minus the width used by the WEST
and EAST, and the height is the height of the panel minus the height that is used
and EAST, and the height is the height of the panel minus the height that is used
to NORTH and SOUTH. The component’s preferred size is ignored.
to NORTH and SOUTH. The component’s preferred size is ignored.

3131
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Fonts
Fontsand
andcolors
Colors

InInthis
thiscase,
case,there
thereisisplaced
placed55JLabel
JLabelcomponents
componentsininthethepanel,
panel,where
wherea acomponent
componentisiscreated
created
bybythe
themethod
methodcreateLabel().
createLabel().Here
Hereyouyoushould
shouldnote,
note,how
howthethesize
sizeisisdefined,
defined,and
andthat
thatthe
the
values
valuesfor
forwidth
widthand
andheight
heightwhere
wheretheytheyare
areignored
ignoredare
areset
settoto0.0.ItItisisnot
notnecessary
necessaryand
andisis
only
onlydone
donetotoclarify
clarifythat
thatthe
thevalues
valuesisisnot
notused.
used.

Otherwise
Otherwisenote
notehowhowyou
youdefine
definecolors
colorsand
andfonts.
fonts.The
TheColor
Colorclass
classhas
hasa anumber
numberofofconstants
constants
for
forfrequently
frequentlyused
usedcolors,
colors,and
andmost
mostofofthe
thecolors
colorsininthis
thisexample
exampleareareindicated
indicatedbybymeans
means
ofofthese
thesecolors.
colors.Colors
Colorsare
aredefined
definedusing
usingthree
threeintensities
intensitiesofofred,
red,green
greenandandblue,
blue,and
andwee
wee
talk about this color coding as RGB colors. Each intensity has a value between
talk about this color coding as RGB colors. Each intensity has a value between 0 and 255,0 and 255,
and
andthethenumber
numberofofpossible
possiblecolors
colorsisis

The
Thefollowing
followingtable
tableshows
showssome
someexamples
examplesofofcolor
colorencodings
encodings

RR GG BB Farve
Farve

00 00 00 Black
Black

255
255 255
255 255
255 White
White

255
255 00 00 Red
Red

00 255
255 00 Green
Green

00 00 255
255 Blue
Blue

255
255 255
255 00 Yellow
Yellow

128
128 128
128 128
128 Gray
Gray

Here
Hereyouyouneed
needtotospecifically
specificallynote
notethe
thelast
lastencoding,
encoding,where
wherethe
thesame
samevalue
valuefor
forallallintensities
intensities
provides
providesa agrayscale.
grayscale.InInJava
Javayou
youcan
candefine
definea acolor
colorasasananobject
objecttotothe
thetype
typeColor
Colorwithwithcolor
color
intensities to the constructor. It is used in the label that sits center in the window
intensities to the constructor. It is used in the label that sits center in the window where where
there
thereisisdefined
definedthe
thefollowing
followingcolor:
color:

new Color(240, 240, 240)

This
Thismeans
meansthat
thatthe
thecomponent
componentwill
willhave
havea afaint
faintgray
graybackground.
background.

You
Youdefine
definea afont
fontfrom
fromthe
thefont
fontname,
name,whether
whetherititshould
shouldbebenormal,
normal,italic,
italic,bold
boldororpossibly
possibly
a acombination of the last two. Finally, you specify the font size.
combination of the last two. Finally, you specify the font size.

3232
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Fonts and Colors
GRAPHICAL USER INTERFACE Fonts and colors

You
You should
should note
note that
that this
this time
time the
the program
program do
do not
not define
define any
any event
event handling.
handling. It
It is
is of
of
course
course because it is
because it is aa simple demo program,
simple demo program, and in practice GUI programs always
and in practice GUI programs always have
have
an
an event
event handling.
handling.

Finally, in the
Finally, in the constructor
constructor you
you should
should note
note the
the statement:
statement:

setLocationRelativeTo(null);

It
It is
is aa statement
statement that
that ensures
ensures that
that the
the window
window opens
opens in
in the
the middle
middle of
of the
the screen.
screen.

EXERCISE
EXERCISE 3
3
Make
Make aa copy
copy of
of the
the program
program TextColor.
TextColor. You
You should
should modify
modify the
the 5 JLabel components
5 JLabel components so
so

1. North
1. North must
must use
use aa Liberation
Liberation Sans
Sans font
font that
that is
is bold
bold and
and 16
16 point.
point.
2. South must have a dark green text color.
2. South must have a dark green text color.
3. West
3. West must
must have
have aa width
width on
on 100
100 and
and aa font
font on
on 48
48 point.
point.
4. East must have a standard yellow text color.
4. East must have a standard yellow text color.
5. Center
5. Center must
must have
have at
at light
light gray
gray background
background and
and aa gray
gray text
text color.
color.

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

33
33
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Dialog boxes

4 DIALOG BOXES
In the above examples are each time been a single window, but in practice, a GUI program
have several or many windows, and in this chapter I will show how you from a window can
open another window. The main window is called a frame window, and is derived from the
class JFrame. Another window, is usually a dialog box, which is a class derived from JDialog.
I will show a program that has three windows:

Here is MainView a usual frame window, which in this case must have two buttons, which
are used to open each of the other two windows:

The window to the right is an example of a dialog box where you should enter a name
(first name and last name):

It must be a modal dialog, and it means that when the dialog box is open, the other windows
of the application does not have focus, and you can not interact with the other windows
before this dialog box is closed.

34
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Dialog
dIalogboxes
boxes

The
Thethird
thirdwindow
windowmust
mustalso
alsobebea adialog
dialogand
andhas hastotoshow
showa alist
listbox
boxwith
withthe
thenames
namesthat
that
have
havebeen
beenentered
entered(see
(seebelow),
below),but
butititmust
mustbebea amodless
modlessdialog
dialogbox,
box,which
whichmeans
meansthat
thatother
other
windows can get focus while the dialog box is
windows can get focus while the dialog box is open.open.

Dialog
Dialogboxes
boxesarearedefined
defined(almost)
(almost)the
thesame
sameway
wayasasframe
framewindows,
windows,and andasassuch
suchthere
thereisis
nothing
nothingnewnewininthe
theprogram,
program,but
butthe
thethree
threewindows
windowshas hastotocommunicate,
communicate,sosothat
thatififyou
you
enter a name in the dialog box above, then dialog box with the list box must be
enter a name in the dialog box above, then dialog box with the list box must be updated updated
with
withthe
theentered
enteredname.
name.

The
Theprogram
programshould
shouldrepresent
representa aname
nameasasananobject,
object,and
andfor
forthat
thatI Ihave
haveused
usedthe
theclass
class
Name
Namefrom
fromthe
theprogram
programComparison
Comparisonininthe
thebook
bookJava
Java1.1.The
Theclass
classisissimple
simpleand
andcompletely
completely
unchanged
unchangedand
andisistherefore
thereforenot
notdiscussed
discussedfurther
furtherhere.
here.

I’ll
I’llstart
startwith
withthe
thedialog
dialogbox
boxfor
forentering
enteringa aname:
name:

package dialogs;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

3535
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Dialog boxes
GRAPHICAL USER INTERFACE dIalog boxes

public class EnterView extends JDialog


{
private DefaultListModel model;
private JTextField txtFirstname = new JTextField();
private JTextField txtLastname = new JTextField();

public EnterView(DefaultListModel model)


{
super(null, "Enter a name", Dialog.ModalityType.APPLICATION_MODAL);
this.model = model;
setSize(400, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createView();
setVisible(true);
}

private void createView()


{
setLayout(new BorderLayout());
JPanel panel = new JPanel(new BorderLayout(0, 20));
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.add(createTop(), BorderLayout.NORTH);

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

36
36
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Dialog boxes
GRAPHICAL USER INTERFACE dIalog boxes

panel.add(createBottom());
add(panel);
}

private JPanel createTop()


{
JPanel panel = new JPanel(new GridLayout(2, 1, 0 ,10));
panel.add(createLine("First name", txtFirstname));
panel.add(createLine("Last name", txtLastname));
return panel;
}

private JPanel createBottom()


{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
panel.add(createButton("OK", 90, 25, this::ok));
panel.add(createSpace());
panel.add(createButton("Close", 90, 25, this::close));
return panel;
}

private JPanel createLine(String text, JTextField field)


{
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel(text);
label.setPreferredSize(new Dimension(90, 22));
panel.add(label, BorderLayout.WEST);
panel.add(field);
return panel;
}

private JButton createButton(String text, int width, int height,


ActionListener listener)
{
JButton cmd = new JButton(text);
cmd.addActionListener(listener);
cmd.setPreferredSize(new Dimension(width, height));
return cmd;
}

private JLabel createSpace()


{
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(10, 20));
return label;
}

37
37
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Dialog
dIalog boxes
boxes

private void clear()


{
txtFirstname.setText("");
txtLastname.setText("");
txtFirstname.requestFocus();
}
private void ok(ActionEvent e)
{
String firstname = txtFirstname.getText().trim();
String lastname = txtLastname.getText().trim();
if (firstname.length() > 0 && lastname.length() > 0)
{
model.addElement(new Name(firstname, lastname));
clear();
}
else JOptionPane.showMessageDialog(this,
"You must enter both first name and last name",
"Error", JOptionPane.WARNING_MESSAGE);
}

private void close(ActionEvent e)


{
dispose();
}
}

The class is called EnterView, and the first thing to note is that the class inherits JDialog
The class is called EnterView, and the first thing to note is that the class inherits JDialog
instead of JFrame. It is telling that it is a dialog box. There are three instance variables, to
instead of JFrame. It is telling that it is a dialog box. There are three instance variables, to
the two input fields and a model for a list box. It may seems strange, since the dialog box
the two input fields and a model for a list box. It may seems strange, since the dialog box
does not contain a list box, but it must be used to keep the Name objects to be displayed
does not contain a list box, but it must be used to keep the Name objects to be displayed
in the second dialog. The model is sent as a parameter in the constructor. Aside from that,
in the second dialog. The model is sent as a parameter in the constructor. Aside from that,
there is not much new in the constructor, but you must notice the first line, which is the
there is not much new in the constructor, but you must notice the first line, which is the
place where one says that it is a modal dialog box by sending a parameter to the constructor
place where one says that it is a modal dialog box by sending a parameter to the constructor
of JDialog. Finally, note the statement setDefaultCloseOperation(), which uses a different
of JDialog. Finally, note the statement setDefaultCloseOperation(), which uses a different
parameter, indicating that if you click the cross in the title bar, then the dialog box must
parameter, indicating that if you click the cross in the title bar, then the dialog box must
be closed, and the program should not terminate.
be closed, and the program should not terminate.

Then there is the method createView(), which initializes the window components. As in the
Then there is the method createView(), which initializes the window components. As in the
other examples, it is spread out in several methods and is certainly complex enough, but
other examples, it is spread out in several methods and is certainly complex enough, but
conversely, there is not much new compared to what was previously mentioned. However,
conversely, there is not much new compared to what was previously mentioned. However,
you should datailed study how the user interface is defined and, in particular, observe what
you should datailed study how the user interface is defined and, in particular, observe what
happens to the window when you run the program and changes the window size.
happens to the window when you run the program and changes the window size.

38
38
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH AA
GRAPHICAL USER
USER INTERFACE
JAVA 2: PROGRAMS
GRAPHICAL WITH A
INTERFACE Dialog
dIalog boxes
boxes
GRAPHICAL USER INTERFACE dIalog boxes

However,
However, there
there isis one
one place
place where
where there
there areare added
added something
something new.new. The
The dialog
dialog box
box has
has two
two
However,
buttons, there is one place where there are added something new. The dialog box has two
buttons, andand they
they must
must have
have attached
attached event
event handlers.
handlers. InIn the
the preceding
preceding examples,
examples, II have
have
buttons, and handlers
attached they must have attached event handlers. In the preceding examples, I have
attachedevent
event handlersfor forbuttons
buttonsat ateither
eitherdefining
defininginner
innerclasses
classesor
orbybydefining
defininganonymous
anonymous
attached
classes. event handlers for buttons at either defining inner classes or byclasses
defining anonymous
classes. Inner classes requires to be written much code and anonymous classes results in
Inner classes requires to be written much code and anonymous results in code
code
classes.
that Inner classes requires to be written much code and anonymous classes results in code
that can
can be
be hard
hard to to read.
read. However,
However, there
there areare alternatives
alternatives and
and inin this
this example,
example, II have
have used
used
aathat can be hard
simple
simple and
and readable
to read. However,
readable notation.
notation. If,If, as
thereexample,
as an
are alternatives
an example, the the event
and in this for
event handler
example,
handler for the
I have used
the Close
Close button,
button,
a simple
there and readable notation. If,that
as an example, the event handler for box.
the Close button,
there shall be no more statements that a statement that close the dialog box. You do this
shall be no more statements a statement that close the dialog You do this
therethe
with shall be no more
statement statements
dispose(), and I that a the
added statement
followingthatmethod:
close the dialog box. You do this
with the statement dispose(), and I added the following method:
with the statement dispose(), and I added the following method:
private void close(ActionEvent e)
{private void close(ActionEvent e)
{dispose();
} dispose();
}

Here you must notice the parameter, which is the one that says that this method can be
Here
Here you
you must
must notice
notice the
the parameter,
parameter, which
which isis the
the one
one that
that says
says that
that this
this method
method can
can be
be
used as an event handler. It must be attached to the button, which is done in the following
used
usedasasan
anevent
eventhandler.
handler.ItItmust
mustbe
beattached
attachedtotothe thebutton,
button,which
whichisisdone
doneininthe
thefollowing
following
way in the method createBottom():
way
wayininthe
themethod
methodcreateBottom():
createBottom():
this::close
this::close

39
39
39
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Dialog
dIalogboxes
boxes

Simpler
Simplerititcan
canhardly
hardlybe.
be.What
Whatexactly
exactlyhappens,
happens,I Iwill
willnot
notexplain
explainhere,
here,but
butininprinciple
principle
what
whathappens
happensisisthat
thatthe
thecompiler
compilerautomatically
automaticallygenerates
generatesthe thecode
codethat
thatI Iusually
usuallywrite.
write.AA
more
moredetailed
detailedexplanation
explanationfollows
followsininthe
thebook
bookJava
Java4,4,but
butthe
thenotation
notationenhances
enhancesreadability
readability
sosomuch that I would recommend that you start taking it as is and use it
much that I would recommend that you start taking it as is and use it already. already.

There
Thereisisaasimilar
similarevent
eventhandler
handlerfor
forthe
thesecond
secondbutton.
button.ItItisisobviously
obviouslymore
moreextensive,
extensive,but
but
shortly
shortlythethefollowing
followinghappens.
happens.The
Theentered
enteredvalues
valuesarearecopied
copiedtotovariables
variablesfrom
fromthe
thetwo
twoinput
input
fields. If there is typed something for both first and last name a Name object
fields. If there is typed something for both first and last name a Name object is created, is created,
and
andthe
themodel
modelisisupdated.
updated.IfIfnot
notaamessage
messagebox
boxdisplays
displaysananerror
errormessage.
message.

Then
Thenthere
thereisisthe
theother
otherdialog
dialogbox,
box,showing
showingthe
theentered
enterednames:
names:

package dialogs;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class ShowView extends JDialog


{
private DefaultListModel model;
private CloseListener listener;

public ShowView(DefaultListModel model, CloseListener listener)


{
super(null, "Names", Dialog.ModalityType.MODELESS);
this.model = model;
this.listener = listener;
setSize(400, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new ClosingHandler());
createView();
setVisible(true);
}

private void createView()


{
setLayout(new BorderLayout());
JPanel panel = new JPanel(new BorderLayout(0, 20));
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.add(new JScrollPane(new JList(model)));
panel.add(createBottom(), BorderLayout.SOUTH);
add(panel);
}

40
40
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Dialog
dIalogboxes
boxes

private JPanel createBottom()


{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
panel.add(createButton("Close", 90, 25, this::close));
return panel;
}

private JButton createButton(String text, int width, int height,


ActionListener listener)
{
JButton cmd = new JButton(text);
cmd.addActionListener(listener);
cmd.setPreferredSize(new Dimension(width, height));
return cmd;
}
private void close(ActionEvent e)
{
listener.dialogClosed();
dispose();
}

class ClosingHandler extends WindowAdapter


{
public void windowClosing(WindowEvent e)
{
listener.dialogClosed();
}
}
}

ItItisissimilar
similaraaclass
classthat
thatinherits
inheritsJDialog.
JDialog.There
Thereare
aretwo
twoinstance
instancevariables,
variables,the
thefirst
firstbeing
beingthe
the
model
modeland andthus
thusthe
theobjects
objectsthat
thatmust
mustbebedisplayed
displayedininthe
thelist
listbox,
box,while
whilethe
theother
otherhashasthe
the
type
typeCloseListener.
CloseListener.I Iexplains
explainsthe
thetype
typeininaamoment,
moment,but butvalues
valuesforforboth
bothvariables
variablesarearesent
sent
totothetheconstructor.
constructor.Otherwise,
Otherwise,there
thereisisonly
onlyone
onething
thingtotonote,
note,that
thatthe
thefirst
firstline
linedefines
defines
that it is a modeless dialog box.
that it is a modeless dialog box.

The
Thedesign
designofofthethewindow
windowisisthis thistime
timesimple
simplesince
sinceititisismerely
merelytotoplace
placeaalist
listbox
boxandandaa
button.
button.The Thebutton
buttonisisassigned
assignedan anevent
eventhandler
handlerwithwiththethesame
samesyntax
syntaxasasmentioned
mentionedabove,
above,
but
but there is one complication back. The dialog is opened by clicking a button in themain
there is one complication back. The dialog is opened by clicking a button in the main
window,
window,and andbecause
becauseititisisaamodeless
modelessdialog
dialogbox,
box,youyoucancanclick
clickthe
thebutton
buttonagain
againand andopen
open
the
thedialog
dialogseveral
severaltimes.
times.I Iare
arenot notinterested
interestedininthat,
that,but
butconversely,
conversely,ititmust
mustbebepossible
possibletoto
opened
openedthe thedialog
dialogagain
againififititisisclosed.
closed.ItItisistherefore
thereforenecessary
necessarytotosend
sendaamessage
messageback backtoto
the
themain
mainwindow
windowwhen whenthethedialog
dialogcloses.
closes.AsAsmentioned,
mentioned,the theconstructor
constructorhashasaaparameter
parameter
named
namedlistener
listenerthat
thathas
hasthe
thetypetypeCloseListener.
CloseListener.It’sIt’saasimple
simpleinterface
interfacedefined
definedininthethesame
same
file
fileasasthe
theclass
classMainView:
MainView:

4141
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
JAVA USER
USER INTERFACE
2: PROGRAMS
GRAPHICAL WITH A
INTERFACE Dialog
dIalog boxes
boxes
GRAPHICAL USER INTERFACE dIalog boxes

interface CloseListener
interface
{ CloseListener
{ public void dialogClosed();
} public void dialogClosed();
}

The interface
The interface does
does nothing
nothing more
more than
than define
define aa single
single method,
method, but
but when
when the the dialog
dialog box
box
The interface does nothing more than define a single method, but when the dialog box
through the
through the constructor
constructor get
get an
an object
object of
of this
this type
type the
the dialog
dialog box
box know
know thatthat object
object has
has
through the constructor get an object of this type the dialog box know that object has
such aa method,
such method, and
and can
can thus
thus sent
sent aa notfikation
notfikation when
when the
the dialog
dialog box
box isis closed
closed by
by clicking
clicking
such a method, and can thus sent a notfikation when the dialog box is closed by clicking
the Close
the Close button:
button:
the Close button:
private void close(ActionEvent e)
private
{ void close(ActionEvent e)
{ listener.dialogClosed();
listener.dialogClosed();
dispose();
} dispose();
}

Now the
Now the dialog
dialog box,
box, inin principle,
principle, also
also could
could bebe closed
closed by by clicking
clicking onon the
the cross
cross in
in the
the
Now the dialog box, in principle, also could be closed by clicking on the cross in the
titleline, and
titleline, and in
in this
this case,
case, sending
sending aa similar
similar notification.
notification. It It isis therefore
therefore necessary
necessary to
to capture
capture
titleline, and in this case, sending a similar notification. It is therefore necessary to capture
the event
the event that
that occurs
occurs when
when clicking
clicking on
on the
the cross.
cross. It
It isis aa WindowEvent,
WindowEvent, and and itit occurs
occurs in
in
the event that occurs when clicking on the cross. It is a WindowEvent, and it occurs in
several contexts,
several contexts, but
but above
above II have
have shown
shown how
how to
to catch
catch itit with
with the the class
class CloseHandler.
CloseHandler. Note
Note
several contexts, but above I have shown how to catch it with the class CloseHandler. Note
that the
that the handler
handler must
must be
be associated
associated with
with the
the dialog
dialog box,
box, which
which happens
happens inin the
the constructor:
constructor:
that the handler must be associated with the dialog box, which happens in the constructor:

42
42
42
JAVA 2: PROGRAMS WITH A
JAVA 2:
JAVA 2: PROGRAMS
PROGRAMS WITH
WITH AA
GRAPHICAL USER INTERFACE Dialog boxes
GRAPHICAL USER
GRAPHICAL USER INTERFACE
INTERFACE dIalog boxes
dIalog boxes

addWindowListener(new ClosingHandler());
addWindowListener(new ClosingHandler());

Back
Back isisis the
Back the main
the main window
main window where
window where there
where there isisis not
there not much
not much to
much to explain
to explain as
explain as ititit isisis just
as just an
just an ordinary
an ordinary
ordinary
window
windowwith
window withtwo
with twobuttons:
two buttons:
buttons:

package dialogs;
package dialogs;

import
import java.awt.*;
java.awt.*;
import
import java.awt.event.*;
java.awt.event.*;
import
import javax.swing.*;
javax.swing.*;
import
import javax.swing.border.*;
javax.swing.border.*;

public class
public class MainView
MainView extends
extends JFrame
JFrame implements
implements CloseListener
CloseListener
{
{
private DefaultListModel
private DefaultListModel model
model == new
new DefaultListModel();
DefaultListModel();
private JButton cmdShow;
private JButton cmdShow;

public MainView()
public MainView()
{{
setTitle("Dialogs");
setTitle("Dialogs");
setSize(200, 160);
setSize(200, 160);
setResizable(false);
setResizable(false);
setLocationRelativeTo(null);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createWindow();
createWindow();
setVisible(true);
setVisible(true);
}}

private void
private void createWindow()
createWindow()
{
{
JPanel panel
JPanel panel == new
new JPanel(new
JPanel(new GridLayout(2,
GridLayout(2, 1,
1, 0,
0, 20));
20));
panel.setBorder(new EmptyBorder(20, 20, 20,
panel.setBorder(new EmptyBorder(20, 20, 20, 20));20));
panel.add(createButton("Enter aa name",
panel.add(createButton("Enter name", this::openEnter));
this::openEnter));
panel.add(cmdShow = createButton("Open list", this::openShow));
panel.add(cmdShow = createButton("Open list", this::openShow));
add(panel);
add(panel);
}
}

private JButton
private JButton createButton(String
createButton(String text,
text, ActionListener
ActionListener listener)
listener)
{
{
JButton cmd
JButton cmd == new
new JButton(text);
JButton(text);
cmd.addActionListener(listener);
cmd.addActionListener(listener);
return cmd;
return cmd;
}
}

private void
private void openEnter(ActionEvent
openEnter(ActionEvent e)
e)
{{

43
43
43
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Dialog
dIalog boxes
boxes

new EnterView(model);
}

private void openShow(ActionEvent e)


{
cmdShow.setEnabled(false);
new ShowView(model, this);
}

public void dialogClosed()


{
cmdShow.setEnabled(true);
}
}

There are
There are twotwo instance
instance variables,
variables, respectively
respectively the
the model
model for for the
the list
list box
box and
and aa button.
button.
The model
The model isis sent
sent toto both
both dialog
dialog boxes
boxes and
and the
the button
button isis aa reference
reference to to the
the button
button that
that
opens the
opens the dialog
dialog box
box with
with the
the list.
list. You
You should
should note
note that
that the
the class
class implements
implements the the interface
interface
CloseListener and
CloseListener and must
must therefore
therefore define
define the
the method
method dialogClosed().
dialogClosed(). WhenWhen the the dialog
dialog box
box for
for
the list
the list box
box isis opened,
opened, twotwo things
things happen.
happen. First
First disables
disables the
the button
button soso thethe dialog
dialog box
box can
can
not be
not be opened
opened again,
again, and
and then
then the
the dialog
dialog box
box opens
opens byby sending
sending parameters
parameters as as the
the model
model for
for
the list
the list box
box andand aa reference
reference toto the
the window
window itself,
itself, but
but the
the window
window isis special
special aa CloseListener,
CloseListener,
and therefore
and therefore can can bebe used
used asas aa current
current parameter.
parameter. The
The result
result isis that
that when
when the the dialog
dialog box
box
closes, itit calls
closes, calls the
the method
method dialogClosed(),
dialogClosed(), which
which enables
enables the
the button,
button, andand thethe dialog
dialog box
box can
can
be opened
be opened again.again. When
When you you test
test the
the program,
program, especially
especially noting
noting that
that ifif you
you create
create aa name
name
then the
then the list
list box
box isis updated
updated automatically
automatically without
without youyou must
must do do anything.
anything. The The technique
technique
for that
for that isis hided
hided inin the
the class
class DefaultListModel.
DefaultListModel.

EXERCISE 44
EXERCISE
In this
In this exercise
exercise you
you have
have to
to make
make some
some improvements
improvements to
to the
the program
program above.
above. Start
Start by
by
creating aa copy
creating copy and
and open
open the
the copy
copy in
in NetBeans.
NetBeans.

You should
You should start
start to
to add
add another
another button
button to
to the
the dialog
dialog ShowView
ShowView where
where the
the button
button should
should
delete the
delete the contents
contents ofof the
the list
list box.
box. This
This change
change should
should not
not lead
lead to
to major
major challenges.
challenges.

Next, itit must


Next, must bebe such
such that
that ifif you
you double-click
double-click on
on aa name
name inin the
the list
list box,
box, then
then the
the dialog
dialog
box EnterView
box EnterView should
should opens
opens initialized
initialized with
with the
the name
name thatthat isis clicked
clicked on,
on, and
and you
you should
should
then be
then be able
able to
to edit
edit the
the name.
name. It It isis immediately
immediately aa little
little more
more complicated,
complicated, butbut you
you can
can go
go
as follows.
as follows.

Modify the
Modify the class
class Name,
Name, so
so itit has
has set
set methods
methods for
for both
both variables.
variables.

44
44
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
JAVA 2: PROGRAMS WITH A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Dialog
dIalog boxes
boxes
GRAPHICAL USER INTERFACE dIalog boxes

Add
Add aaa parameter
parameter index
parameter index to
index to the
to the constructor
the constructor in
constructor in the
in the class
the class EnterView:
class EnterView:
EnterView:
Add

public EnterView(DefaultListModel
public EnterView(DefaultListModel model,
model, int
int index)
index)

and store
and store the
store the value
value in
the value in an
an instance
instance variable.
variable. If
If the
the value
value is negative,
negative, it shal
shal indicate
indicate that
that the
and in an instance variable. If the value isis negative, itit shal indicate that the
the
dialog box
dialog box isis used
box is to
used to create
create aaa Name,
to create Name, and
Name, and otherwise
and otherwise
otherwise thethe index
the index isis interpreted
index is interpreted as as the
as the index
the index of
index ofof
dialog used interpreted
the object
the object in
object in the
in the model
the model
model to to be
to be edited.
be edited. Note
edited. Note that
Note that the
that the change
the change means
change means
means that that itit isis necessary
that it to
necessary toto
the is necessary
change the
change the class
the class MainView
class MainView
MainView where where you
where you must
you must
must addadd a parameter
add aa parameter (value
parameter (value
(value -1)-1) when
-1) when
when the the dialog
the dialog
dialog
change
box EnterView
box EnterView opens.
EnterView opens.
opens.
box

In the
In the class
the class ShowView
class ShowView add
ShowView add the
add the following
the following inner
following inner class:
inner class:
class:
In

class MouseHandler
class MouseHandler extends
extends MouseAdapter
MouseAdapter
{{
public void
public void mouseClicked(MouseEvent
mouseClicked(MouseEvent e)
e)
{{
JList list
JList list == (JList)e.getSource();
(JList)e.getSource();
if (e.getClickCount()
if (e.getClickCount() ==== 2)
2)
{{
int nn == list.locationToIndex(e.getPoint());
int list.locationToIndex(e.getPoint());

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

45
45
45
JAVA
JAVA2:2:
JAVA 2:PROGRAMS
PROGRAMSWITH
PROGRAMS WITHAA
WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
GRAPHICALUSER
GRAPHICAL USERINTERFACE
USER INTERFACE
INTERFACE Dialog
dIalogboxes
dIalog boxes
boxes
GRAPHICAL USER INTERFACE dIalog boxes

JOptionPane.showMessageDialog(null,
JOptionPane.showMessageDialog(null, model.getElementAt(n));
model.getElementAt(n));
JOptionPane.showMessageDialog(null, model.getElementAt(n));
}
}
}
}
}
}
}
}
}

ItItdefines
definesan
defines anevent
an eventhandler
event handlerconcerning
handler concerningmouse
concerning mouseclicks,
mouse clicks,and
clicks, andmust
and mustbe
must belinked
be linkedto
linked tothe
thelist
the listbox,
list box,
ItIt defines an event handler concerning mouse clicks, and must be linked toto the list box,
box,
which
which you
whichyouyou can
youcancan do
candodoby
dobybychanging
changing
bychanging the
the
changingthe method
method
themethod createView():
createView():
methodcreateView():
createView():
which
JList
JList list
list =
= new
new JList(model);
JList(model);
JList list = new JList(model);
list.addMouseListener(new
list.addMouseListener(new MouseHandler());
MouseHandler());
list.addMouseListener(new MouseHandler());
panel.add(new JScrollPane(list));
panel.add(new JScrollPane(list));
panel.add(new JScrollPane(list));

Before
Before continuing,
Beforecontinuing,
continuing,you you should
youshould
shouldtest test the
testthe program.
theprogram. Create
Createaaaafew
program.Create few
fewnamesnames
namesandand open
andopen the
openthe dialog
thedialog
dialog
Before continuing, you should test the program. Create few names and open the dialog
with
with the
withthe list
thelist box.
listbox. Try
box.Try double-clicking
Trydouble-clicking
double-clickingon on
onaaaaname
name
nameandand see
seeififif
andsee you
ifyou get
getaaaamessage
youget message box
messagebox that
boxthat
that
with the list box. Try double-clicking on name and see you get message box that
displays
displays the
displaysthe name.
thename. Doing
name.Doing
Doingso so
sois is everything
everything regarding
everythingregarding double-click
regardingdouble-click
double-clickinto into place.
intoplace.
displays the name. Doing so isiseverything regarding double-click into place.
place.

The
The above
Theabove
aboveevent event handler
eventhandler
handlerfor for the
forthe
themousemouse should
mouseshould
shouldnow now
nowbe be changed,
bechanged,
changed,so so
soit itdoes
does
doesnotnot
notopen open
openaaaa
The above event handler for the mouse should now be changed, so itit does not open
message
message
messagebox, box,
box,but but instead
butinstead opens
insteadopens EnterView,
opensEnterView,
EnterView,where where
wherethe the last
thelast parameter
lastparameter
parameternow now
nowis isthe
the index
theindex
indexof ofthe
the
message box, but instead opens EnterView, where the last parameter now isisthe index ofofthe
the
name
name
namethatthat
thatis is double
double clicked.
doubleclicked. EnterView
clicked.EnterView
EnterViewshould should
shouldshow show
showthe the
thename,name,
name,andand
andto to dodo this,
dothis, change
this,change
changein in
name that isis double clicked. EnterView should show the name, and toto do this, change inin
the
the method
themethod createTop()
methodcreateTop()
createTop()so so that
sothat
thatit itinitializes
initializes
initializesthe the input
theinput
inputfieldsfields
fieldswithwith the
withthe name
thename
namethat that
thatis isdouble-
double-
the method createTop() so that itit initializes the input fields with the name that isis double-
double-
clicked.
clicked. Remember
clicked.Remember
Rememberthat that the
thatthe variable
thevariable
variableindex index
indexis isthe
the index
theindex
indexof ofthe the Name
theName object
Nameobject relative
objectrelative
relativeto tothe
the
clicked. Remember that the variable index isis the index ofof the Name object relative toto the
the
model.
model.
model.WhenWhen
Whenyou you then
youthen click
thenclick OK,
clickOK,
OK,do do
donot not create
createaaaanew
notcreate new
newName Name object,
Nameobject,
object,butbut
butthe the object
theobject
objectthat that
thatis is
model. When you then click OK, do not create new Name object, but the object that isis
clicked
clicked
clickedmustmust instead
mustinstead
insteadbebe updated.
beupdated.
updated.It Itisistherefore
therefore necessary
thereforenecessary
necessaryto tomodify
modify
modifythethe event
theevent handler
eventhandler
handlerok() ok()
clicked must instead be updated. ItItisistherefore necessary totomodify the event handler ok()
ok()
so that
sosothat
thatit it (using
(using
(usingthe the variable
thevariable index)
variableindex) distinguishes
index)distinguishes
distinguishesbetweenbetween
betweenthe the two
thetwo cases,
twocases,
cases,wherewhere
whereto to create
createaaaa
create
so that itit(using the variable index) distinguishes between the two cases, where totocreate
new
new object,
newobject,
object,and and where
andwhere
wherean an existing
anexisting object
existingobject
objectis isedited.
edited.
new object, and where an existing object isisedited.
edited.

Once
Once you’ve
Onceyou’ve made
you’vemade these
madethese changes,
thesechanges,
changes,youyou will
youwill find
willfind
findthatthat the
thatthe list
thelist box
listbox does
boxdoes
doesnotnot seem
notseem
seemto tobe
be updated,
beupdated,
Once you’ve made these changes, you will find that the list box does not seem totobe updated,
updated,
but
but close
butclose the
closethe dialog
thedialog
dialogbox box ShowView
boxShowView
ShowViewand and open
andopen
openit it again,
again, and
again,and
andyou you will
youwill now
willnow
nowseesee that
seethat the
thatthe changes
thechanges
but close the dialog box ShowView and open ititagain, and you will now see that the changes
changes
are
are visible,
arevisible,
visible,soso the
sothe model
themodel
modelhas has therefore
hastherefore been
thereforebeen updated.
beenupdated.
updated.To To solve
Tosolve this
solvethis problem,
thisproblem,
problem,youyou must
youmust add
mustadd
add
are visible, so the model has therefore been updated. To solve this problem, you must add
the
the following
thefollowing
followingclassclass
classto tofile
file with
filewith the
withthe main
themain window:
mainwindow:
the following class totofile with the main window:
window:
class
class EnhancedListModel
EnhancedListModel extends
extends DefaultListModel
DefaultListModel
class EnhancedListModel extends DefaultListModel
{
{
{
public
public void
void update(int
update(int index)
index)
public void update(int index)
{
{
{
fireContentsChanged(this,
fireContentsChanged(this, index,
index, index);
index);
fireContentsChanged(this, index, index);
}
}
}
}
}
}

4646
46
46
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE dIalog
Dialog boxes

It is a class that extends DefaultListModel with a new method. You must also change the
definition of the model in the MainView:

private DefaultListModel model = new EnhancedListModel();

The new method on the model must be called in the event handler ok() in the class EnterView
after the object has been updated:

((EnhancedListModel)model).update(index);

Note the typecast. After that the list box will be updated correctly.

You must add one last improvement. The dialog box EnterView must have an additional
button to be used to delete the object being edited, but the button must only be enabled
if the dialog box is used to edit a Name.

47
47
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE More components

5 MORE COMPONENTS
In this section I will show an example that, in principle is similar to the first examples, where
the program simply consists of a single window, but it is a somewhat more complex example:

1. there are several components both in terms of the number of componentes and
the type of components
2. it is an example of a complex layout
3. there is a comprehensive event management

If you run the program it opens the following window:

The window should illustrate a sign with a text. You can then using the window’s other
components to adjust how the sign should be displayed:

-- the font used to draw the text


-- how the text is aligned (left, right or center)
-- the color used to draw the text
-- the background color to the sign

48
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE More components

Compared to the first examples, this example use more kinds of components:

-- JLabel, which is a component showing a text and was used in the previous examples
-- JTextField, which is an input field, and is also used in the previous examples
-- JComboBox, which is component with a list of objects, and you can then select
one of these objects
-- JCheckBox, which is a simple component, where you can select a property
-- JRadioButton, where several components are organized in a group, so you can
choose one of them
-- JSlider, which is a component, where you by means of the “shoots” can select a
value within a range

If on top of that you adds the components JButton and JList that is used in the previous
examples, but are not used in this example, you have actually met most of the basic Swing
components, and in practice you will get far with these components.

Then there is the program code, which is extensive with nearly 350 lines. Rather than show
alle the code together, I will show parts in connection with the description of the individual
concepts. It is recommended that you open the full code while you read the following.

I’ll start with the layout, which this time is quite complex. You should start to run the
application and notice how some of the components change their sizes as the window size
changes. The components size and location are determined by the layout manager being used,
and it is the subject of the next chapter, but for now I have mentioned three layout managers

-- BorderLayout
-- FlowLayout
-- GridLayout

and they are all used in this example. By using nested layout managers, that is having panels
inside each other with their own layout managers, you can actually by using the above three
layout managers design a rather complicated layout.

49
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
JAVA 2:
2: PROGRAMS
GRAPHICAL
JAVA PROGRAMS WITH A
USER INTERFACE
WITH A More components
GRAPHICAL USER INTERFACE More CoMponents
GRAPHICAL USER
GRAPHICAL USER INTERFACE
INTERFACE More CoMponents
More CoMponents

The
Thestarting
startingpoint
pointisis
issimilar
similartoto
tothe
theprevious
previousexamples
examplesand
andstarts
startswith
withthe
thefollowing
followingmethod:
method:
The
The starting
starting point
point similar
is similar the
to the previous
previous examples
examples and
and starts
starts with
with the
the following
following method:
method:
private void
private void createWindow()
createWindow()
private void createWindow()
{
{{
JPanel panel
JPanel panel = new
new JPanel(new
JPanel(new BorderLayout());
BorderLayout());
JPanel panel == new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(10,
panel.setBorder(new EmptyBorder(10, 10, 10,
EmptyBorder(10, 10,
10, 10, 10));
10));
panel.setBorder(new 10, 10));
panel.add(createTop(), BorderLayout.NORTH);
panel.add(createTop(), BorderLayout.NORTH);
panel.add(createTop(), BorderLayout.NORTH);
panel.add(createCenter());
panel.add(createCenter());
panel.add(createCenter());
add(panel);
add(panel);
add(panel);
}
}}

thatby
that bymeans
meansofof of a BorderLayout
BorderLayout with
with a margin
margin around
around dividing
dividing thethe window
window into
into two
two parts,
parts,
that
that by
by means
means of aaaBorderLayout
BorderLayout with
with aaamargin
margin around
around dividing
dividing thethe window
window into
into two
two parts,
parts,
wherethe
where thetoptophashasaaapanel
panelwith
withallallofof
of the
the adjustment
adjustment components,
components, while
while at at the
the bottom
bottom
where
where the
the top
top has
has panel
a panel with
with all
all of the
the adjustment
adjustment components,
components, whilewhile atat the
the bottom
bottom
hasthe
has thesign,
sign,and
andititit will
will use
use the
the part
part ofof the
the window,
window, which
which is notnot used
used for
for the
the top
top panel.
panel.
has
has the
the sign,
sign, and
and it will
will use
use the
the part
part ofof the
the window,
window, which
which isisisnot
not used
used for
for the
the top
top panel.
panel.

I’llstart
I’ll startwith
withthe
thebottom
bottompanel,
panel,which
whichisis
is the
the simplest.
simplest. The
The sign
sign is represented
represented by
by a JLabel
JLabel
I’ll
I’ll start
start with
with the
the bottom
bottom panel,
panel, which
which is the
the simplest.
simplest. The
The sign
sign isisisrepresented
represented by
by aaaJLabel
JLabel
definedasas
defined as an
an instance
instance variable:
variable:
defined
defined as an
an instance
instance variable:
variable:
private JLabel
private JLabel lblText
lblText == new
new JLabel("Det
JLabel("Det er
er teksten");
teksten");
private JLabel lblText = new JLabel("Det er teksten");

Thebottom
The bottompanel
panelisis
is created
created by
by the
the following
following method:
method:
The
The bottom
bottom panel
panel is created
created by
by the
the following
following method:
method:
private JPanel
private JPanel createCenter()
createCenter()
private JPanel createCenter()
{
{{
lblText.setOpaque(true);
lblText.setOpaque(true);
lblText.setOpaque(true);
lblText.setBackground(Color.white);
lblText.setBackground(Color.white);
lblText.setBackground(Color.white);
JPanel panel
JPanel panel = new
new JPanel(new
JPanel(new BorderLayout());
BorderLayout());
JPanel panel == new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(20,
panel.setBorder(new EmptyBorder(20,
EmptyBorder(20, 0,0, 20,
0, 20, 0));
0));
panel.setBorder(new 20, 0));
JPanel sign
JPanel sign = new
new JPanel(new
JPanel(new BorderLayout());
BorderLayout());
JPanel sign == new JPanel(new BorderLayout());
sign.setBorder(new LineBorder(Color.black));
sign.setBorder(new LineBorder(Color.black));
LineBorder(Color.black));
sign.setBorder(new
JPanel inner
JPanel inner = new
inner == new JPanel(new BorderLayout());
new JPanel(new
JPanel(new BorderLayout());
JPanel BorderLayout());
inner.setBorder(new LineBorder(Color.white,
inner.setBorder(new LineBorder(Color.white, 5));
LineBorder(Color.white, 5));
5));
inner.setBorder(new
inner.add(createDots(), BorderLayout.NORTH);
inner.add(createDots(), BorderLayout.NORTH);
inner.add(createDots(), BorderLayout.NORTH);
inner.add(createDots(), BorderLayout.SOUTH);
inner.add(createDots(), BorderLayout.SOUTH);
BorderLayout.SOUTH);
inner.add(createDots(),
inner.add(createMargin(), BorderLayout.WEST);
inner.add(createMargin(), BorderLayout.WEST);
inner.add(createMargin(), BorderLayout.WEST);
inner.add(createMargin(), BorderLayout.EAST);
inner.add(createMargin(), BorderLayout.EAST);
BorderLayout.EAST);
inner.add(createMargin(),
inner.add(lblText);
inner.add(lblText);
inner.add(lblText);
sign.add(inner);
sign.add(inner);
sign.add(inner);
panel.add(sign);
panel.add(sign);
panel.add(sign);
return panel;
return panel;
return panel;
}
}}

50
50
50
50
JAVA 2: PROGRAMS WITH A
GRAPHICAL
JAVA USER INTERFACE
2: PROGRAMS WITH A More components
GRAPHICAL USER INTERFACE More CoMponents

The first thing that happens is that the panel’s background is set to white. The panel has a
The first thingwith
BorderLayout thatahappens is that the panel’s
nested BorderLayout background
with another is set
nested to white. The
BorderLayout. Thepanel hasalla
goal of
BorderLayout with
this is to define somea nested BorderLayout
margins. The outer with
panelanother nestedofBorderLayout.
has a margin 20 on the top The
andgoal of all
bottom.
this
The ismiddle
to define some
panel margins.
(called sign) The outer panel
is intended has a margin
to define a thin of 20 on
black the top
frame. Thisand bottom.
is done by
The middle panel (called sign) is intended to define a thin black frame. This
assigning a LineBorder, which by default is a line of 1 pixel. Then there is the inner panel is done by
assigning a LineBorder,
called inner. It has a whitewhich by default
margin is a line
of 5 pixels (toofcreate
1 pixel. Then to
distance there
the isblack
the inner
frame.panel
The
called inner. It has a white margin of 5 pixels (to create distance to the
panel places in the corners some small squares (to symbolize screw holes) and finally the black frame. The
panel places in the
label component cornerscenter.
is placed some small squares
To build it all(to
thesymbolize
following screw
methodsholes)
are and
used:finally the
label component is placed center. To build it all the following methods are used:

private JLabel createMargin()


{
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(5, 5));
label.setOpaque(true);
label.setBackground(Color.white);
return label;
}

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

51
51
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
JAVA USER
USERINTERFACE
2: PROGRAMS
GRAPHICALPROGRAMS WITH A
A
INTERFACE More
Morecomponents
CoMponents
JAVA 2: WITH
GRAPHICAL USER
GRAPHICAL USER INTERFACE
INTERFACE More CoMponents
More CoMponents

private JPanel createDots()


private
private
{ JPanel createDots()
JPanel createDots()
{{ JPanel panel = new JPanel(new BorderLayout());
JPanel
JPanel panel == new
panel new JPanel(new
JPanel(new
panel.add(createDot(), BorderLayout());
BorderLayout());
BorderLayout.WEST);
panel.add(createDot(),
panel.add(createDot(), BorderLayout.WEST);
panel.add(createDot(), BorderLayout.WEST);
BorderLayout.EAST);
panel.add(createDot(),
panel.add(createDot(), BorderLayout.EAST);
BorderLayout.EAST);
panel.add(createMargin());
panel.add(createMargin());
panel.add(createMargin());
return panel;
return panel;
}return panel;
}}
private JLabel createDot()
private
private
{ JLabel createDot()
JLabel createDot()
{{ JLabel label = new JLabel();
JLabel
JLabel label == new
label new JLabel();
JLabel();
label.setPreferredSize(new Dimension(5, 5));
label.setPreferredSize(new
label.setPreferredSize(new
label.setOpaque(true); Dimension(5, 5));
Dimension(5, 5));
label.setOpaque(true);
label.setOpaque(true);
label.setBackground(Color.black);
label.setBackground(Color.black);
label.setBackground(Color.black);
return label;
} return label;
return label;
}}
The
Thefirst
firstisisused
usedfor
foraaBorderLayout
BorderLayouttotodefine
defineaawhite
whitebackground.
background.The
Thebottom
bottomcreating
creatingthethe
The
The
black first
first
squareis
is used
used for
for
(screw a
a BorderLayout
BorderLayout
hole), while the to
to define
define
middle a
a white
white
creates a background.
background.
panel with The
The
two bottom
bottom
screw creating
creating
holes and the
the
filled
black square (screw hole), while the middle creates a panel with two screw holes and filled
blacka square
black square background
(screw hole),
hole), while
while the
the middle creates a panel with two screw holes and filled
with white (screw
with awhite backgroundbetween
between the middle
the holes.creates a panel with two screw holes and filled
holes.
with aa white
with white background
background between
between the
the holes.
holes.
Then
Thenthere
thereisisthe
thetop
toppanel,
panel,which
whichisissomewhat
somewhatmore
morecomplex.
complex.ItItactually
actuallyconsists
consistsofoffour
four
Then
Then
lines there
there
with is
is
toolsthe
the
thattop
top panel,
panel,
are laid which
which
out is
is
with somewhat
somewhat
a more
more
GridLayout: complex.
complex. It
It actually
actually consists of
consists of four
four
lines with tools that are laid out with a GridLayout:
lines with
lines with tools
tools that
that are
are laid
laid out
out with
with aa GridLayout:
GridLayout:
private JPanel createTop()
private
private
{ JPanel createTop()
JPanel createTop()
{{ JPanel panel = new JPanel(new GridLayout(4, 1));
JPanel
JPanel panel == new
panel new JPanel(new
JPanel(new GridLayout(4,
panel.add(createFont()); GridLayout(4, 1));
1));
panel.add(createFont());
panel.add(createFont());
panel.add(createFg());
panel.add(createFg());
panel.add(createFg());
panel.add(createBg());
panel.add(createBg());
panel.add(createBg());
panel.add(createText());
panel.add(createText());
panel.add(createText());
return panel;
return panel;
}return panel;
}}

I’ll start with the bottom line, which defines the input field to the text of the sign. The
I’llstart
I’ll
I’ll startwith
withthe
thebottom
bottomline,
line,which
whichdefines
definesthe
theinput
inputfield
fieldto
tothe
thetext
textofof
ofthe
thesign.
sign.The
The
fieldstart with
is definedthe
as bottom line,
an instance which
variable: defines the input field to the text the sign. The
fieldisis
field
field isdefined
definedasas
defined asan
aninstance
an instancevariable:
instance variable:
variable:
private JTextField txtText = new JTextField();
private JTextField
private JTextField txtText
txtText == new
new JTextField();
JTextField();

52
52
52
52
JAVA 2: PROGRAMS WITH A
JAVA 2:
JAVA 2: PROGRAMS
GRAPHICAL PROGRAMS WITH AA
WITH
USER INTERFACE More components
GRAPHICAL USER
GRAPHICAL USER INTERFACE
INTERFACE More CoMponents
More CoMponents

and the panel with the input field is created as follows:


and the
and the panel
panel with
with the
the input
input field
field isis created
created as
as follows:
follows:

private JPanel
private JPanel createText()
createText()
{{
txtText.setText(lblText.getText());
txtText.setText(lblText.getText());
JPanel panel
JPanel panel == new
new JPanel(new
JPanel(new BorderLayout(10,
BorderLayout(10, 0));
0));
panel.setBorder(new EmptyBorder(5,
panel.setBorder(new EmptyBorder(5, 0,
0, 5,
5, 0));
0));
JLabel label
JLabel label == new
new JLabel("Tekst");
JLabel("Tekst");
panel.add(new JLabel("Tekst"),
panel.add(new JLabel("Tekst"), BorderLayout.WEST);
BorderLayout.WEST);
panel.add(txtText);
panel.add(txtText);
return panel;
return panel;
}}

The input field is initialized with the content of the label component to the sign, but
The input
The inputthis
otherwise field
field isis initialized
initialized
is primarily with the
with the content
a BorderLayout content
with aof of theand
the
label label
label component
component
a input to the
to
field, added thecenter.
sign, but
sign, but
In
otherwise
otherwise this
this is
is primarily
primarily aa BorderLayout
BorderLayout with
with
this way one obtains that the field follows the window size. aa label
label and
and a a input
input field,
field, added
added center.
center. In
In
this way
this way one
one obtains
obtains thatthat the
the field
field follows
follows the
the window
window size.size.
Then there is the line to the background color, which consists of a JLabel, and three pairs
Then there
Then there
consisting ofisaisJLabel,
the line
the line toathe
to
and the background
background
JSlider. color,method
color,
The following which consists
which consistssuch
creates of aaa JLabel,
of JLabel,of
couple and
and three pairs
three pairs
components:
consistingof
consisting ofaaJLabel,
JLabel,and
andaaJSlider.
JSlider.The
Thefollowing
followingmethod
methodcreates
createssuch
suchaacouple
coupleof
ofcomponents:
components:

private JPanel
private JPanel createColor(String
createColor(String text,
text, int
int width,
width, JSlider
JSlider slider,
slider,
int min,
int min, int
int max,
max, int
int value)
value)
{{
JPanel panel
JPanel panel == new
new JPanel(new
JPanel(new BorderLayout());
BorderLayout());
JLabel label
JLabel label == new
new JLabel("
JLabel(" "" ++ text);
text);
label.setPreferredSize(new Dimension(width,
label.setPreferredSize(new Dimension(width, 30));
30));
panel.add(label, BorderLayout.WEST);
panel.add(label, BorderLayout.WEST);
slider.setMinimum(min);
slider.setMinimum(min);
slider.setMaximum(max);
slider.setMaximum(max);
slider.setValue(value);
slider.setValue(value);
slider.setMajorTickSpacing(50);
slider.setMajorTickSpacing(50);
slider.setMinorTickSpacing(10);
slider.setMinorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintTicks(true);
panel.add(slider);
panel.add(slider);
return panel;
return panel;
}}

53
53
53
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE components
More CoMponents

The first parameter specifies the text of the label component and the next the width of the
component. The other four parameters are for the slider component and the values it must
be initialized with. A JSlider is a component that represents an interval of integers defined
with setMinimum() and setMaximum(). The component has at any time a value within this
range, and it can be defined with setValue(). The two methods setMajorTickSpacing() and
setMinorTickSpacing() are used to define a visual partition of the component. The method
createColor() returns a JPanel with a BorderLayout containing the label component and the
slider. The result is that the sliders size will follow the width of the panel.

This method is used by the following method to define three pairs of label and slider:

private JPanel createColors(JSlider sldRed,


JSlider sldGreen, JSlider sldBlue,
int red, int green, int blue)
{
JPanel panel = new JPanel(new GridLayout(1, 3));
panel.add(createColor("Rød", 40, sldRed, 0, 255, red));
panel.add(createColor("Grøn", 50, sldGreen, 0, 255, green));
panel.add(createColor("Blå", 40, sldBlue, 0, 255, blue));
return panel;
}

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

54
JAVA 2: PROGRAMS WITH A
JAVA
JAVA 2:
2: PROGRAMS
GRAPHICAL WITH
WITH A
USER INTERFACE
PROGRAMS A More components
JAVA 2:
GRAPHICALPROGRAMS
USER WITH
WITH A
INTERFACE More
JAVA 2: PROGRAMS
GRAPHICAL A
USER INTERFACE More CoMponents
CoMponents
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE More
More CoMponents
CoMponents

They are laid out with a GridLayout with 1 row and 3 columns, and each pair will always
They
They are
are laid out
laidThe with
with aaacomponents
outJSlider GridLayout with
GridLayout with
with 1 row and 3 columns, and each pair will always
fill
They
Theytheare
same.
are laid
laid out
out with
with a GridLayout
GridLayout with 111 row
row and
are defined
row
and
and 333 columns,
columns,
as instance
columns,
and each
variables:
and
and
each pair
each
pair will
pair
will always
will
always
always
fill
fill the
the same.
same. The
The JSlider
JSlider components
components are
are defined
defined as
as instance
instance variables:
variables:
fill
fill the
the same.
same. The
The JSlider
JSlider components
components are
are defined
defined asas instance
instance variables:
variables:
private
private JSlider
JSlider sldRbg
sldRbg == new
new JSlider(JSlider.HORIZONTAL);
JSlider(JSlider.HORIZONTAL);
private
private JSlider
JSlider sldRbg
sldRbg
sldGbg =
== new
new JSlider(JSlider.HORIZONTAL);
JSlider(JSlider.HORIZONTAL);
private JSlider sldGbg new JSlider(JSlider.HORIZONTAL);
private
private JSlider
JSlider sldGbg
sldGbg
sldBbg =
== new
new JSlider(JSlider.HORIZONTAL);
JSlider(JSlider.HORIZONTAL);
private JSlider sldBbg new JSlider(JSlider.HORIZONTAL);
private
private JSlider
JSlider sldBbg
sldBbg =
= new
new JSlider(JSlider.HORIZONTAL);
JSlider(JSlider.HORIZONTAL);
After
Afterthat
thatisisthe
theline
linefor
foradjusting
adjustingthe
thebackground
backgroundcolor
colordefined
definedasasfollows:
After that
After that is
is the
the line
line for
for adjusting
adjusting the
the background
background color
color defined as follows:
defined as follows:
After that is the line for adjusting the background color defined as follows:
follows:
private
private JPanel
JPanel createBg()
createBg()
private
private
{{ JPanel
JPanel createBg()
createBg()
{
{ JPanel
JPanel panel
panel == new
new JPanel(new
JPanel(new BorderLayout());
BorderLayout());
JPanel
JPanel panel
panel =
= new
new
panel.setBorder(new JPanel(new
JPanel(new BorderLayout());
BorderLayout());
panel.setBorder(new EmptyBorder(5,
EmptyBorder(5, 0,
0, 5,
5, 0));
0));
panel.setBorder(new
panel.setBorder(new
JLabel label = new EmptyBorder(5,
EmptyBorder(5, 0,
0, 5,
5,
JLabel("Baggrungsfarve");0));
0));
JLabel label = new JLabel("Baggrungsfarve");
JLabel
JLabel label
label == new
new JLabel("Baggrungsfarve");
JLabel("Baggrungsfarve");
label.setPreferredSize(new Dimension(120,
label.setPreferredSize(new Dimension(120, 30));
30));
label.setPreferredSize(new
label.setPreferredSize(new
panel.add(label, Dimension(120,
Dimension(120,
BorderLayout.WEST); 30));
30));
panel.add(label, BorderLayout.WEST);
panel.add(label,
panel.add(label, BorderLayout.WEST);
BorderLayout.WEST);
panel.add(createColors(sldRbg, sldGbg,
panel.add(createColors(sldRbg, sldGbg, sldBbg,
sldBbg, 255,
255, 255,
255, 255));
255));
panel.add(createColors(sldRbg,
panel.add(createColors(sldRbg,
return panel; sldGbg,
sldGbg, sldBbg,
sldBbg, 255,
255, 255,
255, 255));
255));
return panel;
}}return
return panel;
panel;
}
}

The
The goal
Thegoal of
goalofof all
ofall this
allthis is
thisisis to
istoto ensure
toensure that
ensurethat the
thatthe slider
theslider components
slidercomponents are
componentsare resized
areresized equally
resizedequally in
equallyinin the
inthe line
theline
line
The
The goal
goal of all
all this
this is to ensure
ensure that
that the
the slider
slider components
components are
are resized
resized equally
equally in the
the line
line
when
when the
the window
window
when the window size
size isis changed.
changed.
window size isis changed.
changed.
when
when the
the window sizesize is changed.
The
The line
Theline to
linetoto define
todefine the
definethe text
thetext color
textcolor is
colorisis designed
isdesigned in
designedinin exactly
inexactly the
exactlythe same
thesame way,
sameway, and
andIIIIwill
way,and will not
willnot show
notshow
show
The
The line
line to define
define the
the text
text color
color is designed
designed in exactly
exactly the
the same
same way,
way, and
and I will
will not
not show
show
ititithere,
here, but
here,but the
butthe three
thethree slider
threeslider components
slidercomponents
componentsare are defined
definedasas
aredefined instance
asinstance variables:
instancevariables:
variables:
it
it here,
here, but
but the
the three
three slider
slider components
components are are defined
defined as
as instance
instance variables:
variables:
private
private JSlider
JSlider sldRfg
sldRfg == new
new JSlider(JSlider.HORIZONTAL);
JSlider(JSlider.HORIZONTAL);
private
private JSlider
JSlider sldRfg
sldRfg
sldGfg =
== new
new JSlider(JSlider.HORIZONTAL);
JSlider(JSlider.HORIZONTAL);
private JSlider sldGfg new JSlider(JSlider.HORIZONTAL);
private
private JSlider
JSlider sldGfg
sldGfg
sldBfg =
== new
new JSlider(JSlider.HORIZONTAL);
JSlider(JSlider.HORIZONTAL);
private JSlider sldBfg new JSlider(JSlider.HORIZONTAL);
private
private JSlider
JSlider sldBfg
sldBfg =
= new
new JSlider(JSlider.HORIZONTAL);
JSlider(JSlider.HORIZONTAL);

Then there
Then there is
there is the
is the top
the top toolbar,
top toolbar, which
toolbar, which is
which is the
is the most
the most complex.
most complex. It
complex. It uses
It uses the
uses the following
the following components,
following components,
components,
Then
Then
Then there
thereis
isthe
thetop
toptoolbar,
toolbar,which
which is
isthe
themost
mostcomplex.
complex.It
Ituses
usesthe
thefollowing
followingcomponents,
components,
all of which
all of which are
which are defined
are defined as instance
defined as instance variables:
instance variables:
variables:
all
allofof
all ofwhich
whichare definedasas
aredefined asinstance
instancevariables:
variables:
private
private JComboBox
JComboBox lstFont;
lstFont;
private
private JComboBox
JComboBox lstFont;
private JTextFieldlstFont;
JTextField txtSize
txtSize == newnew JTextField();
JTextField();
private
private JTextField
JTextField
JCheckBox txtSize
txtSize
chkBold = =
= new
new
new JTextField();
JTextField();
JCheckBox("Bold");
private JCheckBox chkBold = new JCheckBox("Bold");
private
private JCheckBox
JCheckBox chkBold = new JCheckBox("Bold");
private JCheckBox chkBold
chkItalic
chkItalic= = new
= new
newJCheckBox("Bold");
JCheckBox("Italic");
JCheckBox("Italic");
private
private JCheckBox
JCheckBox chkItalic
chkItalic
JRadioButton =
= new
new JCheckBox("Italic");
JCheckBox("Italic");
private JRadioButton cmdLeft = new JRadioButton("Left",
cmdLeft = new JRadioButton("Left", true);
true);
private
private JRadioButton
JRadioButton cmdLeft
cmdLeft =
= new
new JRadioButton("Left",
JRadioButton("Left", true);
true);
private JRadioButton cmdCenter
cmdCenter == new new JRadioButton("Center");
JRadioButton("Center");
private
private JRadioButton
JRadioButton cmdCenter = new JRadioButton("Center");
private JRadioButton cmdCenter
cmdRight === new
cmdRight new JRadioButton("Right");
new JRadioButton("Center");
JRadioButton("Right");
private
private JRadioButton cmdRight = new JRadioButton("Right");
JRadioButton cmdRight = new JRadioButton("Right");

55
55
55
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
JAVA 2: PROGRAMS
GRAPHICAL
GRAPHICAL USER WITH A
USERINTERFACE
INTERFACE More
Morecomponents
CoMponents
GRAPHICAL USER INTERFACE More CoMponents

The
The following
following method
method creates
creates a a JPanel
JPanel with
with a a BorderLayout
BorderLayout containing
containing a a JLabel
JLabel and
and a a
The following method creates a JPanel with a BorderLayout containing a JLabel and a
JComboBox,
JComboBox,andandthe
thegoal
goalisisthat
thatthethecombo
comboboxboxmustmustfollow
followthe
thewidth
widthofofthe
thewindow:
window:
JComboBox, and the goal is that the combo box must follow the width of the window:
private JPanel createFonts()
private JPanel createFonts()
{
{
JPanel panel = new JPanel(new BorderLayout(10, 0));
JPanel panel = new JPanel(new BorderLayout(10, 0));
JLabel label = new JLabel("Fonte");
JLabel label = new JLabel("Fonte");
panel.add(new JLabel("Fonte"), BorderLayout.WEST);
panel.add(new JLabel("Fonte"), BorderLayout.WEST);
DefaultComboBoxModel model = new DefaultComboBoxModel();
DefaultComboBoxModel model = new DefaultComboBoxModel();
String fonts[] =
String fonts[] =
GraphicsEnvironment.getLocalGraphicsEnvironment().
GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames();
getAvailableFontFamilyNames();
for (int i = 0; i < fonts.length; ++i) model.addElement(fonts[i]);
for (int i = 0; i < fonts.length; ++i) model.addElement(fonts[i]);
lstFont = new JComboBox(model);
lstFont = new JComboBox(model);
Font df = label.getFont();
Font df = label.getFont();
for (int n = 0; n < fonts.length; ++n)
for (int n = 0; n < fonts.length; ++n)
if (df.getFamily().equals(fonts[n]))
if (df.getFamily().equals(fonts[n]))
{
{
lstFont.setSelectedIndex(n);
lstFont.setSelectedIndex(n);
break;
break;
}
}
panel.add(lstFont);
panel.add(lstFont);
chkBold.setSelected(df.isBold());
chkBold.setSelected(df.isBold());
chkItalic.setSelected(df.isItalic());
chkItalic.setSelected(df.isItalic());
txtSize.setText("" + (size = df.getSize()));
txtSize.setText("" + (size = df.getSize()));
return panel;
return panel;
}
}

After
Afterthethelabel
labelcomponent
componentisisadded,
added,the themethod
methodcreates
createsa adata
datamodel
modelforforthe
thecombo
combobox.box.
After the label component is added, the method creates a data model for the combo box.
Next,
Next,ananarray
arrayofofthe
thenames
namesofofallallfonts
fontsavailable
availableon onthe
thecurrent
currentmachine
machineisiscreated,
created,and
andthis
this
Next, an array of the names of all fonts available on the current machine is created, and this
array
arrayisisused
usedtotoinitialize
initializethe
themodel.
model.AfterAfterthe
thecombo
combobox boxisiscreated
createdthethelabel
labelcomponent
componentisis
array is used to initialize the model. After the combo box is created the label component is
used
usedtotodetermine
determinethe thecurrent
currentdefault
defaultfontfontforfora aJLabel,
JLabel,and
andititisisused
usedtotodetermine
determinewhich
which
used to determine the current default font for a JLabel, and it is used to determine which
element
elementininthe thecombo
combobox,box,that
thatshould
shouldbebeselected.
selected.Finally,
Finally,the
thedefault
defaultfont
fontisisused
usedtoto
element in the combo box, that should be selected. Finally, the default font is used to
initialize
initializethe
thetwo
twocheck
checkboxes
boxesand
andthe theinput
inputfield
fieldtotothe
thefont
fontsize.
size.
initialize the two check boxes and the input field to the font size.

With
Withthis
thismethod
methodininplace,
place,the
thetoolbar
toolbartotofonts
fontsare
aredefined
definedasasfollows:
follows:
With this method in place, the toolbar to fonts are defined as follows:
private JPanel createFont()
private JPanel createFont()
{
{
JPanel panel = new JPanel(new BorderLayout(10, 0));
JPanel panel = new JPanel(new BorderLayout(10, 0));
panel.setBorder(new EmptyBorder(5, 0, 5, 0));
panel.setBorder(new EmptyBorder(5, 0, 5, 0));
panel.add(createFonts());
panel.add(createFonts());
JPanel east = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
JPanel east = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
east.add(new JLabel("Størrelse"));
east.add(new JLabel("Størrelse"));

5656
56
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE More components
GRAPHICAL USER INTERFACE More CoMponents

txtSize.setPreferredSize(new Dimension(40, 25));


east.add(txtSize);
east.add(chkBold);
east.add(chkItalic);
east.add(new JLabel(" | Justering"));
ButtonGroup group = new ButtonGroup();
group.add(cmdLeft);
group.add(cmdCenter);
group.add(cmdRight);
east.add(cmdLeft);
east.add(cmdCenter);
east.add(cmdRight);
panel.add(east, BorderLayout.EAST);
return panel;
}

Here is not much new to explain, and the method must mainly insert the panel from
Here is not much new to explain, and the method must mainly insert the panel from
createFonts() and the remaining components in a BorderLayout.
createFonts() and the remaining components in a BorderLayout.

After the design is completed – after a long road, but wee also talk about a very complex
After the design is completed – after a long road, but wee also talk about a very complex
design, and by testing you should observe that it is a stable design where the components
design, and by testing you should observe that it is a stable design where the components
adapts to the window size.
adapts to the window size.

57
57
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE More components
GRAPHICAL USER INTERFACE More CoMponents

Back
Backisisevent
eventhandling,
handling,and
andtotohelp
helpwith
withthat,
that,the
theprogram
programprovides
providesthe
thefollowing
followingmethods:
methods:

private Font createNewFont()


{
boolean bold = chkBold.isSelected();
boolean italic = chkItalic.isSelected();
String name = (String)lstFont.getSelectedItem();
int size = Integer.parseInt(txtSize.getText());
if (bold && italic) return new Font(name, Font.BOLD | Font.ITALIC, size);
if (bold) return new Font(name, Font.BOLD, size);
if (italic) return new Font(name, Font.ITALIC, size);
return new Font(name, Font.PLAIN, size);
}

private void alignText()


{
if (cmdLeft.isSelected()) lblText.setHorizontalAlignment(JLabel.LEFT);
else if (cmdCenter.isSelected()) lblText.
setHorizontalAlignment(JLabel.CENTER);
else lblText.setHorizontalAlignment(JLabel.RIGHT);
}

private void foreground()


{
lblText.setForeground(
new Color(sldRfg.getValue(), sldGfg.getValue(), sldBfg.getValue()));
}

private void background()


{
lblText.setBackground(
new Color(sldRbg.getValue(), sldGbg.getValue(), sldBbg.getValue()));
}

The
Thefirst
firstcreates
createsand
andreturns
returnsaafont
fontbased
basedononthe
thesettings
settingsselected
selectedininthe
thetop
toptoolbar.
toolbar.The
Thenext
next
sets the horizontal alignment of the component lblText corresponding to the
sets the horizontal alignment of the component lblText corresponding to the radio button radio button
that
thatisispressed.
pressed.Finally,
Finally,the
thelast
lasttwo
twomethods
methodsdefines
definesthe
thecomponent’s
component’s(the (thesign’s)
sign’s)text
textcolor
color
and background color from the settings for the JSlider components.
and background color from the settings for the JSlider components.

58
58
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE More
Morecomponents
CoMponents

The
Thevarious
variouscomponents
componentscan
canfire
firean
anevent
eventwhen
whenan anaction
actionoccurs,
occurs,and
andininthe
theprevious
previousexamples
examples
I Ihave
haveshown
shownandandused,
used,how
howaabutton
buttoncan
canfire
firean
anActionEvent
ActionEventwhen
whenclicked,
clicked,and
andhow
howthis
this
event
eventcan
canbebecaught
caughtand
andhandled
handledby byan
anActionListener.
ActionListener.InInthis
thisexample
exampleI Iwill
willuse
usethat
that

--- AAJTextField
JTextFieldcan
canfire
fireaaFocusEvent,
FocusEvent,when
whenititget
getthe
thefocus
focus(when
(whenthe
theuser
userselect
selectthe
the
field
fieldby
bythe
thetab
tabkey
keyororthe
themouse),
mouse),and
andwhen
whenititlost
lostfocus
focus(when
(whenthe
theuser
userleave
leavethe
the
field).
field).These
Theseevents
eventscancanbe
becaught
caughtwith
withaaFocusListener.
FocusListener.
--- AAJComboBox
JComboBox firing an ActionEvent, when theselection
firing an ActionEvent, when the selectionisischanged
changed(when
(whenthe theuser
user
select
selectanother
anotherelement),
element),that
thatcan
canbe
becaught
caughtwith
withan anActionListener.
ActionListener.
--- AAJCheckBox
JCheckBoxand andaaJRadioButton
JRadioButtonfiring
firingaaChangeEvent,
ChangeEvent,when whenthe
thestate
stateisischanged,
changed,
and
andititcan
canbebecaught
caughtwithwithaaChangeListener.
ChangeListener.
--- AAJSlider
JSlider fires a ChangeEvent,when
fires a ChangeEvent, whenthethevalue
valueisischanged,
changed,andandititcan
canbe becaught
caught
with
withaaChangeListener.
ChangeListener.

With
Withthis
thisknowledge
knowledgethe
theevent
eventhandlers
handlerscan
canbe
bewritten.
written.They
Theyare
areexcept
exceptfor
foraasingle
singlesimple,
simple,
and they are written therefore as anonymous classes in method addListeners():
and they are written therefore as anonymous classes in method addListeners():

private void addListeners()


{
txtText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e)
{
lblText.setText(txtText.getText());
}
public void focusGained(FocusEvent e)
{
}
});
txtSize.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e)
{
try
{
int t = Integer.parseInt(txtSize.getText());
if (t > 5)
{
lblText.setFont(createNewFont());
return;
}
}
catch (Exception ex)
{
}
txtSize.setText("" + size);
}

5959
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHAA
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE MoreCoMponents
More components

public void focusGained(FocusEvent e)


{
size = Integer.parseInt(txtSize.getText());
}
});
lstFont.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
lblText.setFont(createNewFont());
}
});
chkBold.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
lblText.setFont(createNewFont());
}
});
chkItalic.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
lblText.setFont(createNewFont());
}
});

60
60
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH AA
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE More
More components
CoMponents

cmdLeft.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
alignText();
}
});
cmdCenter.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
alignText();
}
});
cmdRight.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
alignText();
}
});
sldRfg.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
foreground();
}
});
sldGfg.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
foreground();
}
});
sldBfg.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
foreground();
}
});
sldRbg.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
background();
}
});
sldGbg.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
background();
}
});

61
61
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE More
Morecomponents
CoMponents

sldBbg.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e)
{
background();
}
});
}

There is not much to explain, but you must note that a FocusListener defines two methods,
There is not much to explain, but you must note that a FocusListener defines two methods,
both to be implemented. You should also note that the event handler to the input field for
both to be implemented. You should also note that the event handler to the input field for
the font size is relatively complex since it must take into account that the user may enter
the font size is relatively complex since it must take into account that the user may enter
anything illegal. You are invited to test the program and study the code thoroughly, as the
anything illegal. You are invited to test the program and study the code thoroughly, as the
example contains much of what is necessary in practice to write a GUI program.
example contains much of what is necessary in practice to write a GUI program.

EXERCISE 5
EXERCISE 5
Make a copy of the project CreateSign. You have to expand the layout with a new toolbar
Make a copy of the project CreateSign. You have to expand the layout with a new toolbar
(see below). The two combo boxes and associated labels and check box must all have a
(see below). The two combo boxes and associated labels and check box must all have a
fixed size and be placed to the left as shown below. The button must follow the right edge.
fixed size and be placed to the left as shown below. The button must follow the right edge.
The meaning of the new components are as follows. The first combo box should contain
The meaning of the new components are as follows. The first combo box should contain
the colors that are defined as constants in the class Color – except for the colors black and
the colors that are defined as constants in the class Color – except for the colors black and
dark gray. The second combo box should contains the numbers from 3 to 20 inclusive.
dark gray. The second combo box should contains the numbers from 3 to 20 inclusive.
The 4 black square (screw holes) form the corners of a border around the sign. The two
The 4 black square (screw holes) form the corners of a border around the sign. The two
combo boxes indicates respectively the color and width of this edge when the width must
combo boxes indicates respectively the color and width of this edge when the width must
also apply the size of the 4 squares (they must always be black). The check box must be
also apply the size of the 4 squares (they must always be black). The check box must be
used to specify whether the sign should have a transparent background – only the interior
used to specify whether the sign should have a transparent background – only the interior
of the sign and not the edge. Finally, the button is used to restore all settings to default –
of the sign and not the edge. Finally, the button is used to restore all settings to default –
that is, as they were when the program starts.
that is, as they were when the program starts.

Your first task is to add the new toolbar to the program and thus expand the program
Your first task is to add the new toolbar to the program and thus expand the program
with the necessary design. You can start by creating the components and then place them
with the necessary design. You can start by creating the components and then place them
in a panel with a BorderLayout, where the button is placed EAST while the rest of the
in a panel with a BorderLayout, where the button is placed EAST while the rest of the
components are in a FlowLayout, which then is inserted WEST in the first panel.
components are in a FlowLayout, which then is inserted WEST in the first panel.

Next, you define event handlers in addListeners() – four in all. The handler for the JCheckBox
Next, you define event handlers in addListeners() – four in all. The handler for the JCheckBox
component is simple, but there is little problem to getting the component to update itself
component is simple, but there is little problem to getting the component to update itself
when switching from non-transparent to transparent background:
when switching from non-transparent to transparent background:

62
62
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE More components

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

63
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE More components
GRAPHICAL USER INTERFACE More CoMponents
GRAPHICAL USER INTERFACE More CoMponents

public void stateChanged(ChangeEvent e)


public void stateChanged(ChangeEvent e)
{
{
lblText.setOpaque(!chkTrans.isSelected());
lblText.setOpaque(!chkTrans.isSelected());
lblText.repaint();
lblText.repaint();
}
}

Here
Here is the last statement is required for the changes tototake effect. To change the color
Here isis the
the last
last statement
statement is is required
required for for the
the changes
changes to take take effect.
effect. To
To change
change the
the color
color
and
and width
width ofofthethe frame,
frame, ititisisnecessary
necessary totohave
have references
references totothe
the components
components that
that make
make
and width of the frame, it is necessary to have references to the components that make
up
up the frame: The 44black squares and the 44edges. It isiseight in total, and ititisisall JLabel
up the
the frame:
frame: The The 4 black
black squares
squares andand thethe 4 edges.
edges. ItIt is eight
eight inin total,
total, and
and it is all
all JLabel
JLabel
components.
components. Start therefore by defining 88 instance variables for these components and
components. Start therefore by defining 8 instance variables for these components and
Start therefore by defining instance variables for these components and
initialize
initialize them
them totothe
the respective
respective components
components when
when they
they are
are created.
created. Then
Then it’s
it’ssimple
simple totowrite
write
initialize them to the respective components when they are created. Then it’s simple to write
aahandler for the first combo box totochange the color – here, only 44ofofthe 8 components
a handler
handler for for the
the first
first combo
combo box box to change
change the the color
color – – here,
here, only
only 4 of the the 8 8 components
components
must
must change color. As regards to the final combo box that is used to change the components
must change color. As regards to the final combo box that is used to change the components
change color. As regards to the final combo box that is used to change the components
preferred
preferred size isisaalittle more difficult. The following method can be used totochange the size
preferred size is a little more difficult. The following method can be used to change the
size little more difficult. The following method can be used change the size
size
ofofaacomponent
component (the
(the times
times that
that a aJLabel ):
JLabel ):
of a component (the times that a JLabel ):

private void resize(JLabel label, int width)


private void resize(JLabel label, int width)
{
{
label.setPreferredSize(new Dimension(width, width));
label.setPreferredSize(new Dimension(width, width));
label.doLayout();
label.doLayout();
label.revalidate();
label.revalidate();
}
}

Finally, there
thereisis
Finally,there the
isthe button
buttontoto
thebutton the
tothe right.
theright. When
right.When
Whenyouyou click
youclick on
onit,it,
clickon it,all all settings
allsettings should
settingsshould return
returnasas
shouldreturn as
Finally,
at program startup and the sign should be displayed as when the program starts.
atatprogram
programstartup
startupand
andthe
thesign
signshould
shouldbebedisplayed
displayedasaswhen
whenthe theprogram
programstarts.
starts.

64
64
64
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Layout
layout and
and the
tHe component’s
CoMponent’s size
sIze

6 
6 LAYOUT AND THE
COMPONENT’S SIZE
As
As shown
shown in in the
the above
above examples,
examples, aa component’s
component’s size size and and location
location isis determined
determined of of the
the
so-called
so-called layout
layout managers,
managers, and
and the
the result
result isis not
not always
always quite quite so
so easy
easy to to figure
figure out.
out. In
In this
this
section
section II will
will explain
explain in
in part
part how
how aa component’s
component’s size size isis calculated,
calculated, and and also
also where
where itit isis
placed
placed in in the
the window.
window. When
When there
there isis aa lot
lot to
to tell
tell itit isis due
due toto aa desire
desire that that the
the window
window
and
and its
its components
components should
should behave
behave sensibly
sensibly ifif the
the window
window size size changes.
changes. If, If, for
for example
example youyou
consider
consider thethe above
above program
program several
several of
of the
the components
components change change sizes
sizes whenwhen the the window
window isis
resized,
resized, while
while others
others components
components follows
follows thethe window’s
window’s right right edge.
edge. ItIt isis controlled
controlled by by layout
layout
managers,
managers, which
which determines
determines how
how the
the components
components of of aa window
window or or panel
panel are are placed.
placed.

6.1
6.1 THE
THE COMPONENT’S
COMPONENT’S SIZE
SIZE
AA component
component hashas aa size
size which
which isis determined
determined by
by aa width
width and
and aa height,
height, and
and to
to define
define and
and
modify
modify these
these values
values aa component
component hashas four
four methods
methods

--- setSize()
setSize()
--- setPreferredSize()
setPreferredSize()
--- setMinimumSize()
setMinimumSize()
--- setMaximumSize()
setMaximumSize()

These
These methods
methods all all have
have aa parameter
parameter of of the
the type
type Dimension,
Dimension, however,however, the the first
first has
has anan
overloading,
overloading, wherewhere thethe parameters
parameters are are two
two int
int values.
values. The The first
first has
has only
only effect
effect ifif the
the panel
panel
isis not
not using
using aa layout
layout manager.
manager. In In all
all other
other cases
cases itit isis ignored.
ignored. ItIt cancan therefore
therefore be be used
used to
to
define
define thethe size
size of
of the
the window,
window, because
because aa frame
frame Window
Window does does notnot have
have aa layout
layout manager.
manager.
In
In practice
practice areare components
components almost almost always
always placed
placed in in aa panel
panel using
using oneone oror more
more layout
layout
managers,
managers, and and here
here itit isis the
the last
last three
three methods,
methods, which
which are are the
the interesting.
interesting. TheThe main
main rulerule isis
that
that aa layout
layout manager
manager will will try
try toto customize
customize aa component’s
component’s size size toto its
its preferred
preferred size,
size, but
but the
the
manager
manager will will not
not reduce
reduce component
component size size to
to below
below its its minimum
minimum size size and
and not
not increase
increase the the
size
size to
to more
more than
than its
its maximum
maximum size. size. SoSo there
there are
are three
three sizessizes attached
attached to to aa component,
component, but but
the
the whole
whole thing
thing isis complicated
complicated because because how how these
these quantities
quantities are are used
used are
are determined
determined by by the
the
specific
specific layout
layout manager.
manager. As As aa start
start isis shown
shown below
below the the codecode forfor aa window
window withwith 66 buttons:
buttons:

package layoutpanels;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

65
65
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Layout
layout and
and the
tHe component’s
CoMponent’s size
sIze

public class MainView extends JFrame


{
public MainView()
{
setTitle("Components and there locations");
setSize(500, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createWindow();
setVisible(true);
}

private void createWindow()


{
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 30, 10));
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.add(createButton("BorderLayout", 150, 30, null));
panel.add(createButton("FlowLayout", 120, 40, null));
panel.add(createButton("GridLayout", 150, 30, null));
panel.add(createButton("GridBagLayout", 200, 50, null));
panel.add(createButton("BoxLayout", 150, 30, null));
panel.add(createButton("Null layout", 250, 20, null));
add(panel);
}

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

66
66
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

private JButton createButton(String text, int width, int height,


ActionListener listener)
{
JButton cmd = new JButton(text);
cmd.addActionListener(listener);
cmd.setPreferredSize(new Dimension(width, height));
return cmd;
}
}

You should note the method createButton(), which creates a button with a preferred size.
InYou should the
addition, notebutton’s
the method
event createButton(), which creates
handler is a parameter. a buttonis with
The method used ainpreferred size.
createView()
toIncreate
addition, the button’s
the buttons, event
but so handler
far the is a parameter.
last parameter The null,
is always method is used
which in means
simply createView()
that
the button not yet have an event handler, but the meaning is that when you click onthat
to create the buttons, but so far the last parameter is always null, which simply means a
button, it opens another window which illustrates the effect of a layout manager. If youa
the button not yet have an event handler, but the meaning is that when you click on
button,
run it opens you
the program, another window
get the which
following illustrates the effect of a layout manager. If you
window:
run the program, you get the following window:

The method createWindow() creates a panel with a FlowLayout, which is already used several
The method
times createWindow()
as a layout manager that creates
placesa components
panel with a in
FlowLayout,
a row fromwhich
left tois already
right. Isused
thereseveral
not
times as a layout manager that places components in a row from left to right.
enough space, the components continue on the next line, and the component’s size are Is there not
enough space,
determined the components
by their preferred size.continue on the next line, and the component’s size are
determined by their preferred size.

67
67
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE layout
Layout and
and tHe
the CoMponent’s
component’s sIze
size

6.2 BORDERLAYOUT
6.2 BORDERLAYOUT
If you click on the top button, a window opens, whose code is as follows:

package layoutpanels;

import java.awt.*;
import javax.swing.*;

public class BorderlayoutView extends JDialog


{
public BorderlayoutView()
{
super(null, "BorderLayout", Dialog.ModalityType.APPLICATION_MODAL);
setSize(500, 300);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
}

private void createWindow()


{
setLayout(new BorderLayout(10, 20));
setBackground(Color.lightGray);
add(createLabel("North", 0, 30, Color.white, Color.blue), BorderLayout.NORTH);
add(createLabel("South", 0, 40, Color.white, Color.red), BorderLayout.SOUTH);
add(createLabel("West", 80, 0, Color.black, Color.green), BorderLayout.WEST);

68
68
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

add(createLabel("East", 100, 0, Color.white, Color.magenta),


BorderLayout.EAST);
add(createLabel("Center", 0, 0, Color.black, Color.yellow));
}

private JLabel createLabel(String text, int width, int height, Color color1,
Color color2)
{
JLabel label = new JLabel(text);
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(color2);
label.setForeground(color1);
label.setPreferredSize(new Dimension(width, height));
return label;
}
}

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

69
69
JAVA
JAVA2:2:
JAVA 2:PROGRAMS
PROGRAMSWITH
PROGRAMS WITHAA
WITH A
GRAPHICAL
GRAPHICALUSER
GRAPHICAL USERINTERFACE
USER INTERFACE
INTERFACE Layout
layoutand
layout andthe
and tHecomponent’s
tHe CoMponent’ssize
CoMponent’s sIze
sIze

This
Thistime
timeititisisnot
notaaJFrame
JFramewindow,
window,but butaadialog
dialog––the
theclass
classinherits
inheritsJDialog.
JDialog.The
Thedialog
dialog
box
boxhas
hasaaBorderLayout
BorderLayoutwithwithfive
fiveJLabel
JLabelcomponents
components

Above
AboveI Ihave
haveexplained
explainedhowhowaaBorderLayout
BorderLayoutworks,
works,and
andI Iwill
willnot
notfurther
furthercomments
commentson onthat
that
layout
layoutmanager.
manager.ToToopen
openthe
thedialog,
dialog,the
theMainView
MainViewmust
musthave
haveananevent
eventhandler
handlerfor
forthe
thefirst
first
button
buttonand
andthere
thereisisnothing
nothingnew
newcompared
comparedtotowhat
whathas
haspreviously
previouslybeen
beensaid:
said:

private void border(ActionEvent e)


{
new BorderlayoutView();
}

panel.add(createButton("BorderLayout", 150, 30, this::border));

6.3 FLOWLAYOUT
6.3 FLOWLAYOUT
Clicking
Clickingthethesecond
secondtoptopbutton
button(in
(inthe
theMainView),
MainView),you
youget
getaawindow
windowasasshown
shownbelow,
below,toto
illustrate
illustratethe
theuse
useofofaaFlowLayout
FlowLayoutmanager:
manager:

package layoutpaneler;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FlowlayoutView extends JDialog


{
public FlowlayoutView()
{
super(null, "FlowLayout", Dialog.ModalityType.APPLICATION_MODAL);
setSize(500, 300);

7070
70
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

this.setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
}

private void createWindow()


{
setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (char c = 'A'; c <= 'Z'; ++c) add(createButton("" + c, 50, 30));
}

private JButton createButton(String text, int width, int height)


{
JButton cmd = new JButton(text);
cmd.setPreferredSize(new Dimension(width, height));
cmd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(FlowlayoutView.this,
"You have clicked " + text); } });
return cmd;
}
}

Thewindow
The windowisisagain
againaamodal
modaldialog
dialogbox,
box,but
butthis
thistime
timewith
withaaFlowLayout.
FlowLayout.There
Thereare
are27
27
buttons,and
buttons, andthe
theonly
onlything
thingtotowatch
watchisiswhat
whathappens
happenswhen
whenyou
yourun
runthetheprogram
programand
and
changethe
change thewindow
windowsize. size.You
Youcan
canalso
alsonote
notehow
howtotoattach
attachan
ananonymous
anonymouseventeventhandler
handlerfor
for
thebuttons.
the buttons.ItItisisnot
notparticularly
particularlyreadable,
readable,but
butisisaashort
shortway
wayofofwriting.
writing.

71
71
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

6.4 GRIDLAYOUT
A GridLayout is a layout manager that subdivides a panel into a number of rows and a
number of columns. If the panel for example has 10 rows and 20 columns, it contains
200 cells, that all are of the same size. Each cell can contain a component, and the
component will always fill the entire cell, and a GridLayout ignores everything regarding the
components preferred size. Below is a window with 200 components located in the panel
using a GridLayout. The components are all JLabel components, which all is displayed with
a random background color:

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

72
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE layout and the
Layout tHe component’s
CoMponent’s size
sIze

The code is the follewing:

package layoutpaneler;

import java.util.*;
import java.awt.*;
import javax.swing.*;

public class GridlayoutView extends JDialog


{
private static Random rand = new Random();

public GridlayoutView()
{
super(null, "GridLayout", Dialog.ModalityType.MODELESS);
setSize(500, 300);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
}

private void createWindow()


{
setLayout(new GridLayout(10, 20));
for (int r = 0; r < 10; ++r) for (int c = 0; c < 20; ++c) add(createLabel());
}

private JLabel createLabel()


{
JLabel label = new JLabel();
label.setOpaque(true);
label.setBackground(new Color(rand.nextInt(256), rand.nextInt(256),
rand.nextInt(256)));
return label;
}
}

You should
You should note
note how,
how, in
in the
the createWindow()
createWindow() aa GridLayout
GridLayout isis created.
created. The
The parameters
parameters are,
are,
respectively the
respectively the number
number of
of rows
rows and
and number
number ofof columns.
columns. You
You can
can also
also specify
specify how
how much
much
gap there
gap there should
should be
be between
between the
the individual
individual cells
cells –– both
both horizontally
horizontally and
and vertically.
vertically.

73
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

EXERCISE 6
Write a program that you can call MiniCalc. The program must open a window as shown
below. The window has an input field and 20 buttons. The program should simulate a
simple calculator and should only be operated using the mouse. The input field is read
only (use method setEditable()), and the text is right-justified. The 10 top buttons should
be self-explanatory. The buttons in the third row are from left:

1. remove the last character in the display


2. exponentation
3. division
4. subtraction
5. decimal point

The buttons in the bottom row are from left:

1. clear the display


2. shift sign on the content in the display
3. multiplication
4. addition
5. enter, that calculates the value of the expression in the display and update the
display with the value

74
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

The program must validate that there only are added legal characters in the display (character
which leads to a legitimate expression). If you try to perform an illegal calculation by clicking
OK, you should get an error message as shown below:

It is obviously a very simplified calculator, and you can only work with very simple expressions,
especially because you can not enter parentheses.

360°
thinking .

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


75
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

6.5 GRIDBAGLAYOUT
The next layout manager is a very a flexible manager, but is also very complex to work
with. As the name says, it is a grid that divides a panel in row and columns, but such that
all rows do not have to have the same height, and all the columns do not have to have
the same width. The result is the same as in a GridLayout, that the panel is divided into a
number of cells, but a component may this time spans multiple cells. In addition to what
is the exact size of the individual cells is determined by the components’s preferred size.
How much the components fills, and how they behave when the window size is changed,
is determined by a data structure called a GridBagConstraints and an object of this kind
is associated with the individual components. This data structure has the following fields:

1. gridx and gridy indicating the component’s column and row index in the panel as
the upper left corner is (0, 0). You can also specify the value as GridBagConstraints.
RELATIVE for both column and row, which means relative to the last component,
placed in the panel. Default value for both columns and rows are GridBagConstraints.
RELATIVE.
2. gridwidth and gridheight indicating respectively how many columns and how many
rows this component should span. The default value of both values is 1. For both
values it is possible to specify GridBagConstraints.REMAINDER, which means
that the component will span over the remainder of the row or the remainder of
the column.
3. fill that indicates how the component should fill the cell if its preferred size is less
than the size of the cell. You can specify GridBagConstraints.NONE, (which means
that the preferred size is used) GridBagConstraints.HORIZONTAL, GridBagConstraints.
VERTICAL and GridBagConstraints.BOTH where the first is default.
4. ipadx and ipady that indicates how much gap there must be outside of the component.
Default value is 0. You can think of this value as an edge on the component, but
an internal edge which is part of the area that is used for the component.
5. insets which indicates an external margin, and therefore how much space, there
must be around of the component. The value is a Insets object, and the default is
no margin.
6. weightx and weighty indicating how the space will be distributed on respectively
columns and rows. The impact of these values is a little difficult to interpret, but
they have a value between 0 and 1, where the default is 0. This means that the
width of columns and the height of the rows is the maximum preferred width and
the maximum preferred height of the components in the column or row. If, you for
a component indicates a weight, this means that any free space in the panel should
be distributed corresponding to these weights. The weights are therefore central to
how the components will behave when the window is resized.

76
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

7. anchor as in the case where the component’s preferred size is less than the cell
indicates where the component is to be placed in the cell. The options are shown in
the figure below, where the names all refer to the constants in GridBagConstraints:

The above sounds complicated, and it also is, and it takes some experimentation to get a
GridBagLayout to behave as desired. The starting point is to start with a sketch, which can
illustrate the window that you want to design. In this case I would design a window where
you can enter the number of units and unit price of an item. One must also be able to
check whether the unit price is entered with or without VAT. When you click on a button,
the program must calculate the total and VAT, and if you click on another button, a line
item is inserted in a list box. The design should be something like what is shown as below:

The three fields under the list box must contain totals for the product lines. The list box
and the three fields to the totals should follow the window size and the buttons should be
positioned relative to the bottom.

77
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Layout
layout and
and the
tHe component’s
CoMponent’s size
sIze

In
In fact,
fact, itit isis aa quite
quite complex
complex design
design andand itit isis an
an example
example of of aa design
design that
that can
can be
be solved
solved
with
with aa GridBagLayout.
GridBagLayout. The The code
code isis shown
shown below,
below, and and itit fills
fills much:
much:

package layoutpanels;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class GridbaglayoutView extends JDialog


{
private DefaultListModel model = new DefaultListModel();
private ButtonGroup group = new ButtonGroup();
private JTextField txtUnits;
private JTextField txtPrice;
private JTextField txtExcl;
private JTextField txtVAT;
private JTextField txtIncl;
private JRadioButton cmdExcl;
private JRadioButton cmdIncl;
private JTextField txtExclSum;
private JTextField txtVATSum;
private JTextField txtInclSum;

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

78
78
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHAA
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE Layoutand
layout andtHe
theCoMponent’s
component’ssIze
size

private double units;


private double price;
private double excl;
private double vat;
private double incl;
private double exclSum;
private double vatSum;
private double inclSum;

public GridbaglayoutView()
{
super(null, "GridBagLayout", Dialog.ModalityType.APPLICATION_MODAL);
setSize(800, 500);
this.setMinimumSize(new Dimension(800, 450));
this.setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
}

private void createWindow()


{
setLayout(new BorderLayout());
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(new EmptyBorder(20, 20, 30, 20));
addComponent(panel, createLabel("Number of units", 120, 20), 0, 0, 2, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new Insets(0, 0, 0, 0));
addComponent(panel, txtUnits = createField(120, 20, true), 2, 0, 1, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new Insets(0, 0, 20, 20));
addComponent(panel, createLabel("Unit price", 120, 20), 0, 1, 2, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new Insets(0, 0, 0, 0));
addComponent(panel, txtPrice = createField(120, 20, true), 2, 1, 1, 1, 0, 0,
GridBagConstraints.HORIZONTAL, GridBagConstraints.LINE_START,
new Insets(0, 0, 20, 20));
addComponent(panel, cmdExcl = createRadio("Unit price excl. VAT", 200, 20,
true, group), 0, 2, 3, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new Insets(0, 0, 10, 0));
addComponent(panel, cmdIncl = createRadio("Unit price incl. VAT", 200, 20,
false, group), 0, 3, 3, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new Insets(0, 0, 20, 0));
addComponent(panel, createLabel("Amount", 100, 20), 0, 4, 1, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.FIRST_LINE_START,
new Insets(0, 0, 0, 0));

7979
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

addComponent(panel, txtExcl = createField(150, 20, false), 1, 4, 2, 1, 0, 0,


GridBagConstraints.NONE, GridBagConstraints.LINE_END,
new Insets(0, 0, 20, 20));
addComponent(panel, createLabel("VAT", 100, 20), 0, 5, 1, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.FIRST_LINE_START,
new Insets(0, 0, 0, 0));
addComponent(panel, txtVAT = createField(150, 20, false), 1, 5, 2, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.FIRST_LINE_END,
new Insets(0, 0, 20, 20));
addComponent(panel, createList(), 3, 0, 3, 7, 1, 1, GridBagConstraints.BOTH,
GridBagConstraints.LINE_START, new Insets(0, 0, 10, 0));
addComponent(panel, createLabel("Total", 100, 20), 0, 6, 1, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.FIRST_LINE_START,
new Insets(0, 0, 0, 0));
addComponent(panel, txtIncl = createField(150, 20, false), 1, 6, 2, 1, 0, 0,
GridBagConstraints.NONE, GridBagConstraints.FIRST_LINE_END,
new Insets(0, 0, 20, 20));
addComponent(panel, createLabel("Amount", 80, 20), 3, 7, 1, 1, 1, 0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new Insets(0, 0, 0, 0));
addComponent(panel, createLabel("VAT", 80, 20), 4, 7, 1, 1, 1, 0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new Insets(0, 0, 0, 0));
addComponent(panel, createLabel("Total", 80, 20), 5, 7, 1, 1, 1, 0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new Insets(0, 0, 0, 0));
addComponent(panel, createButton("OK", 90, 23, this::ok), 0, 9, 1, 1, 0, 0,
GridBagConstraints.HORIZONTAL, GridBagConstraints.LINE_START,
new Insets(20, 0, 0, 10));
addComponent(panel, createButton("Clear", 90, 23, this::clear), 1, 9, 1, 1, 0,
0, GridBagConstraints.HORIZONTAL, GridBagConstraints.LINE_START,
new Insets(20, 0, 0, 10));
addComponent(panel, createButton("Calculate", 90, 23, this::calc), 2, 9, 1, 1,
0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.LINE_START,
new Insets(20, 0, 0, 40));
addComponent(panel, txtExclSum = createField(100, 20, false), 3, 8, 1, 1, 1, 0,
GridBagConstraints.HORIZONTAL, GridBagConstraints.LINE_START,
new Insets(0, 0, 0, 10));
addComponent(panel, txtVATSum = createField(100, 20, false), 4, 8, 1, 1, 1, 0,
GridBagConstraints.HORIZONTAL, GridBagConstraints.LINE_START,
new Insets(0, 0, 0, 10));
addComponent(panel, txtInclSum = createField(100, 20, false), 5, 8, 1, 1, 1, 0,
GridBagConstraints.HORIZONTAL, GridBagConstraints.LINE_START,
new Insets(0, 0, 0, 0));
addComponent(panel, createButton("Delete", 90, 23, this::delete), 5, 9, 1, 1,
0, 0, GridBagConstraints.NONE, GridBagConstraints.LINE_END,
new Insets(20, 0, 0, 0));

80
80
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHAA
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE Layoutand
layout andtHe
theCoMponent’s
component’ssIze
size

add(panel);
}
private JScrollPane createList()
{
JList list = new JList(model);
list.setEnabled(false);
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(400, 200));
return scroll;
}

private JRadioButton createRadio(String text, int width, int height,


boolean checked, ButtonGroup group)
{
JRadioButton cmd = new JRadioButton(text);
cmd.setPreferredSize(new Dimension(width, height));
cmd.setSelected(checked);
group.add(cmd);
return cmd;
}

AXA Global
Graduate Program
Find out more and apply

8181
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

private JLabel createLabel(String text, int width, int height)


{
JLabel label = new JLabel(text);
label.setPreferredSize(new Dimension(width, height));
return label;
}

private JButton createButton(String text, int width, int height,


ActionListener listener)
{
JButton cmd = new JButton(text);
cmd.setPreferredSize(new Dimension(width, height));
cmd.addActionListener(listener);
return cmd;
}

private JTextField createField(int width, int height, boolean editable)


{
JTextField field = new JTextField();
field.setPreferredSize(new Dimension(width, height));
field.setEditable(editable);
field.setHorizontalAlignment(JTextField.RIGHT);
return field;
}

public static void addComponent(Container container, Component component,


int gridx, int gridy, int gridwidth, int gridheight, double weightx,
double weighty, int fill, int anchor, Insets insets)
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = gridx;
constraints.gridy = gridy;
constraints.gridwidth = gridwidth;
constraints.gridheight = gridheight;
constraints.weightx = weightx;
constraints.weighty = weighty;
constraints.fill = fill;
constraints.anchor = anchor;
constraints.insets = insets;
container.add(component, constraints);
}

private void calc(ActionEvent e)


{
try
{
units = Double.parseDouble(txtUnits.getText().trim());

82
82
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHAA
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE Layoutand
layout andtHe
theCoMponent’s
component’ssIze
size

price = Double.parseDouble(txtPrice.getText().trim());
if (units > 0 && price > 0)
{
if (cmdIncl.isSelected()) price *= 0.8;
excl = price * units;
vat = excl * 0.25;
incl = excl + vat;
txtExcl.setText(String.format("%1.2f", excl));
txtVAT.setText(String.format("%1.2f", vat));
txtIncl.setText(String.format("%1.2f", incl));
return;
}
}
catch (Exception ex)
{
}
JOptionPane.showMessageDialog(this,
"Illegal value for the number of units or unit price",
"Error message", JOptionPane.ERROR_MESSAGE);
}

private void ok(ActionEvent e)


{
if (incl > 0)
{
model.addElement(String.format(
"%1.1f units á kr. %1.2f, amount = %1.2f, VAT = %1.2f, total = %1.2f",
units, price, excl, vat, incl));
exclSum += excl;
vatSum += vat;
inclSum += incl;
txtExclSum.setText(String.format("%1.2f", exclSum));
txtVATSum.setText(String.format("%1.2f", vatSum));
txtInclSum.setText(String.format("%1.2f", inclSum));
clear(e);
}
}

private void clear(ActionEvent e)


{
units = price = excl = incl = vat = 0;
txtUnits.setText("");
txtPrice.setText("");
txtExcl.setText("");
txtVAT.setText("");
txtIncl.setText("");
txtUnits.requestFocus();
}

83
83
JAVA 2:
JAVA 2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Layout
layout and
and the
tHe component’s size
CoMponent’s sIze

private void delete(ActionEvent e)


{
model.clear();
clear(e);
}
}

The window contains this time many components:


The window contains this time many components:

-- 8 label components that are objects of the type JLabel


- 8 label components that are objects of the type JLabel
-- 8 input fields that are objects of the type JTextField
- 8 input fields that are objects of the type JTextField
-- 2 radio buttons that are objects of the type JRadioButton
- 2 radio buttons that are objects of the type JRadioButton
-- 1 list box that is an object of the type JList
- 1 list box that is an object of the type JList
-- 4 buttons that are objects of the type JButton
- 4 buttons that are objects of the type JButton

If you start at the top, there is a model for the list box and a ButtonGroup. The last object
If you start at the top, there is a model for the list box and a ButtonGroup. The last object
should be used for the radio buttons that are attached to a ButtonGroup. This ensures that
should be used for the radio buttons that are attached to a ButtonGroup. This ensures that
only one radio button can be pressed. Next, are defined the components that you could
only one radio button can be pressed. Next, are defined the components that you could
refer to in the event handlers. It is the input fields and the two radio buttons (actually only
refer to in the event handlers. It is the input fields and the two radio buttons (actually only
one of them). Final is defined variables to the values of the input fields.
one of them). Final is defined variables to the values of the input fields.

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

84
84
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

The class has several auxiliary methods:

-- createLabel() is a simple method that creates a label with a preferred size.


-- createField() creates in the same way an input field. It has a parameter that specify
where the content can be edited. That is where the field should be used for input
or it only should be used to show a value. You should note that the content is
right aligned.
-- createRadio() is a method that creates a radio button. It has a parameter that tells
if the button should be checked, and also the group is a parameter. The group is
required, because a window may well have more groups of radio buttons.
-- createButton() is a method that creates a button and there are parameters for the
text, the size and the event handler.
-- createList() creates the list box and encapsulates the list box in a JScrollPane, so you
will be able to scroll the content.

Furthermore, there is defined four event handlers for the four buttons:

1. calc() is event handler to the button Calculate. When pressing it retrieves the contents
of the input fields respectively the number of units and the unit price and converts
the values and stored them in the respective variables. If entered legal values, the
VAT if necessary pulled out of the unit price, and otherwise the product amounts
and VAT are calculated and the corresponding fields are updated. Are the values
of the one reason or another illegal, you gets an error message.
2. clear() is event handler to the Clear button, and it clears the input fields and fields
to the result and set the variables used for the calculation to zero.
3. ok() is event handler for the OK button. If there is a calculation, the method add
a line to the list box for the current item and updates the fields for the totals. The
method also call the handler clear() and clears the calculation fields.
4. delete() is event handler to the Delete button and clears the list box.

Now there’s the method createWindow(), and that is where it all happens. To add a component
the method uses a method called addComponent(). This method creates a GridBagConstraints
object and initialize it using parameters. This object is attached to the component, which
is then added to the panel. createWindow() creates a JPanel with a GridBagLayout. In order
to have a margin the panel is assigned a border, but otherwise the work consists of placing
the 23 components in the panel. I will not go through all 23 components, but I’ll look at
two as the principle is much the same for all components.

85
JAVA 2: PROGRAMS WITH A
JAVA
JAVA 2:
2: PROGRAMS
GRAPHICAL WITH
WITH A
USER INTERFACE
PROGRAMS A Layout and the component’s size
GRAPHICAL USER INTERFACE
GRAPHICAL USER INTERFACE layout
layout and
and tHe
tHe CoMponent’s
CoMponent’s sIze
sIze

I’ll start with the second component, which is the input field to the number of units:
I’ll
I’ll start
start with
with the
the second
second component,
component, which
which is
is the
the input
input field
field to
to the
the number
number of
of units:
units:

addComponent(panel,
addComponent(panel, txtUnits
txtUnits =
= createField(120,
createField(120, 20,
20, true),
true), 2,
2, 0,
0, 1,
1, 1,
1, 0,
0, 0,
0,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, GridBagConstraints.LINE_START,
new
new Insets(0,
Insets(0, 0,
0, 20,
20, 20));
20));

The
The input field is created with aa suitable preferred size. This has implications for the size
The input
input field
field is is created
created with
with a suitable
suitable preferred
preferred size. size. This
This has
has implications
implications for for the
the sizesize
of
of the cell that contains the component. Then is defined that the cell should be column 2,
of the cell that contains the component. Then is defined that the cell should be column 2,
the cell that contains the component. Then is defined that the cell should be column 2,
row
row 0.
0. When
When itit isis placed
placed in
in column
column 2,
2, itit isis because
because the
the label
label component
component in
in front
front og
og itit isis
row 0. When it is placed in column 2, it is because the label component in front og it is
spanning
spanning two columns. The next two parameters indicates that this component does not need
spanning two two columns.
columns. The The next
next two
two parameters
parameters indicates indicates that that this
this component
component does does not
not need
need
to
to span
span the
the cells
cells other
other than
than the
the cell
cell in
in which
which itit isis placed.
placed. The
The next
next two
two parameters
parameters again,
again,
to span the cells other than the cell in which it is placed. The next two parameters again,
are
are the weights, and they indicate with the next fill parameter, the size of this component
are the
the weights,
weights, and and they
they indicate
indicate with
with the the nextnext fill fill parameter,
parameter, the the size
size ofof this
this component
component
must
must always be its preferred size. The second last parameter tells that the component must
must always be its preferred size. The second last parameter tells that the component must
always be its preferred size. The second last parameter tells that the component must
be
be adjusted to the left side of the cell, and finally the last parameter indicates that there
be adjusted
adjusted to to thethe left
left side
side ofof the
the cell,
cell, and
and finally
finally the the last
last parameter
parameter indicates
indicates that
that there
there
has
has to
to be
be aa margin
margin of
of 20
20 to
to the
the right
right of
of and
and below
below the
the component.
component.
has to be a margin of 20 to the right of and below the component.

Below
Below is the code that adds the list box:
Below is
is the
the code
code that
that adds
adds the
the list
list box:
box:

addComponent(panel,
addComponent(panel, createList(),
createList(), 3,
3, 0,
0, 3,
3, 7,
7, 1,
1, 1,
1, GridBagConstraints.BOTH,
GridBagConstraints.BOTH,
GridBagConstraints.LINE_START, new
GridBagConstraints.LINE_START, new Insets(0,
Insets(0, 0,
0, 10, 0));
10, 0));

ItIt
It isis placed
is placed
placed inin column
column 33
in column row
3 row
row 0,0, but
but itit
0, but should
it should span
span 33
should span columns
3 columns
columns andand
and 77 rows.
7 rows. Next,
rows. Next, the
Next, the weights
the weights
weights
are
areset
are set to
setto 1,
to1, and
1,and it says
andititsays that
saysthat the
thatthe component
thecomponent
componentmust must
mustuse use all
useall the
allthe available
theavailable
availablespacespace both
spaceboth horizontally
bothhorizontally
horizontally
and vertically.
and vertically.
and vertically. AtAt the
At the same
the same time
same time telling
time telling the
telling the next
the next parameter,
next parameter,
parameter, thethe component
the component
component shouldshould fill
should fill the
fill the
the
entire
entire cell
entire cell out
cell out both
out both horizontally
both horizontally
horizontally and and vertically,
and vertically,
vertically, andand the
and the result
the result is that
result isis that the
that the component’s
the component’s
component’s size size
size
follows
follows the
follows the window
the window
window size. size. Its
size. Its preferred
Its preferred
preferred size size is ignored.
size isis ignored.
ignored. The The two
The two
two last last parameters
last parameters tells
parameters tells the
tells the
the
component
component to
component to
to bebe adjusted
be adjusted
adjusted to to the
to the cell’s
the cell’s left
cell’s left edge
left edge (ignored
edge (ignored
(ignored in in this
in this case,
this case, but
case, but the
but the method
the method
method
addComponent()
addComponent() requires
addComponent() requires
requires aaa value),
value), and
value), and there
and there must
there must
must be be
be aaa margin
margin of
margin of
of 10 10 below
10 below the
below the component.
the component.
component.

As
As aaa final
As final note
final note
note toto the
to the dialog
the dialog box,
dialog box, notice
box, notice that
notice that the
that the window
the window in
window in the
in the constructor
constructor isis
the constructor assigned
assigned aaa
is assigned
minimum
minimum size.
minimum size. The
size. The reason
reason isis
The reason not
is not to
not to made
to made the
made the window
the window smaller,
window smaller, then
smaller, then the
then the layout
the layout manager
layout manager
manager
can not
can not
can display
not display the
display the components.
the components.
components.

86
86
86
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

If you opens the dialog box and enter values for a few items, the result could be as shown
below:

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

87
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

EXERCISE 7
EXERCISE 7
Write a program that you can call Positions that opens a window as shown below:
Write a program that you can call Positions that opens a window as shown below:

The user must enter the name and position of a person, and when you click on OK, the
The user must enter the name and position of a person, and when you click on OK, the
program must inserts a line in the list box. The goal of the exercise is that the window
program must inserts a line in the list box. The goal of the exercise is that the window
should be designed using a GridBagLayout. The top entry fields must have a fixed size, but
should be designed using a GridBagLayout. The top entry fields must have a fixed size, but
the list box and the bottom button should follow the window size.
the list box and the bottom button should follow the window size.

You should first create a simple class that represents a person:


You should first create a simple class that represents a person:

package positions;

public class Person


{
private String firstname;
private String lastname;
private String position;

88
88
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Layout
layoutand
andthe
tHecomponent’s
CoMponent’ssize
sIze

public Person(String firstname, String lastname, String position)


{
this.firstname = firstname;
this.lastname = lastname;
this.position = position;
}

public String toString()


{
return firstname + " " + lastname + ", " + position;
}
}

To
Tocreate
createthe
thewindow
windowManView
ManViewyou youcan
cancopy
copythethemethod
methodaddComponent()
addComponent()from fromthetheabove
above
example,
example,andandmaybe
maybeititcan
canalso
alsobe
beaagood
goodidea
ideatotocopy
copythe
themethods
methodscreateLabel(),
createLabel(),createField()
createField()
and
andcreateButton().
createButton().Subsequently,
Subsequently,thethewindow
windowmay maybebedesigned
designedininthethesame
samemanner
mannerasasinin
the
theabove
aboveexample.
example.I Imay
maymention
mentionthat
thatmy
myGridBagLayout
GridBagLayouthas hasfive
fiverows
rowsand
andfour
fourcolumns.
columns.

6.6 BOXLAYOUT
6.6 BOXLAYOUT
The
Thenext
nextlayout
layoutmanager
managerisisininprinciple
principleaavery
verysimple
simplelayout
layoutmanager,
manager,butbutisisalso
alsocomplex,
complex,
asasthere
thereare
aremany
manyoptions,
options,andandititcancanbe
bedifficult
difficulttotofigure
figureout
outhow
howthethedifferent
differentsettings
settings
affects
affectsthe
thelayout.
layout.Basically,
Basically,ititisisaalayout
layoutmanager
managerthatthatorganizes
organizesits
itscomponents
componentsininaarow row
either horizontally or vertically. Immediately it looks like a FlowLayout, but there
either horizontally or vertically. Immediately it looks like a FlowLayout, but there are some are some
more
morethings
thingstotobe
beaware
awareof.
of.

When
WhenaaBoxLayout
BoxLayoutorganize
organizecomponents,
components,their
theirlocation
locationand
andsize
sizewill
willbe
bedetermined
determinedby
by

--- the
thecomponent’s
component’spreferred
preferredsize
size
--- the
thecomponent’s
component’sminimum
minimumsize size
--- the
thecomponent’s
component’smaximum
maximumsize size
--- the component’s alignment
the component’s alignment

ItItisisbest
bestillustrated
illustratedthrough
throughexamples,
examples,and
andififyou
youclick
clickthe
thebutton
buttonBoxLayout
BoxLayoutininthe
thedemo
demo
program,
program,you yougetgetaawindow
windowwhere
whereyou
youcan
canopen
open11 11examples
examples(se(sebelow).
below).Here
Hereare
arethe
thefirst
first
10 examples virtualy the same, while the latter is a little different. The window’s
10 examples virtualy the same, while the latter is a little different. The window’s buttons buttons
isisalso
alsolaid
laidoutoutusing
usingaaBoxLayout.
BoxLayout.You
Youare
areencouraged
encouragedtotorun runthe
theprogram
programandandsee
seewhat
what
happens
happenswith withthethebuttons
buttonswhen
whenthe
thewindow
windowisisresized.
resized.Here
Hereyouyouparticularly
particularlyshould
shouldnotice
notice
three
threethings:
things:

8989
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

90
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

1.
1.TheThebuttons
buttonsare arelocated
locatedcentered
centeredininthethewindow.
window.WhenWhenusing
usingaaBoxLayout,
BoxLayout,allallthe
the
container’s components usually have the same aligment as different alignment
container’s components usually have the same aligment as different alignment often often
leads
leadstotounexpected
unexpectedresults.
results.
2.
2. The component’s sizesare
The component’s sizes arenot
notchanged,
changed,butbutisisdefined
definedofoftheir
theirpreferred
preferredsize.
size.This
This
isisbecause
becausethey
theyhave
havethe
thesame
sameminimum,
minimum,maximum
maximumand andpreferred
preferredsize,
size,which
whichthen
then
determines the component’s size. To ensure that a BoxLayout gives
determines the component’s size. To ensure that a BoxLayout gives the expected the expected
result,
result,you
youshould
shouldalways
alwaysspecify
specifyall
allthree
threesizes
sizesofofaacomponent.
component.
3.
3. The part of the window, which is not occupied by componentsisisblank,
The part of the window, which is not occupied by components blank,and
andthe
theblank
blank
space
space(the
(thecomponents
componentsare arelaid
laidout
outininaacolumn)
column)isisalways
alwaysbelow
belowthe
thecomponents.
components.

The
Thewindow
windowcode
codeisisthe
thefollowing,
following,where
whereI Ihave
havenot
notshown
shownthe
theevent
eventhandlers:
handlers:

package layoutpanels;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BoxlayoutView extends JDialog


{
public BoxlayoutView()
{
super(null, "BoxLayout", Dialog.ModalityType.APPLICATION_MODAL);
setSize(300, 330);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
}

private void createWindow()


{
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(createButton("Example 1", 150, 25, this::box01));
panel.add(createButton("Example 2", 150, 25, this::box02));
panel.add(createButton("Example 3", 150, 25, this::box03));
panel.add(createButton("Example 4", 150, 25, this::box04));
panel.add(createButton("Example 5", 150, 25, this::box05));
panel.add(createButton("Example 6", 150, 25, this::box06));
panel.add(createButton("Example 7", 150, 25, this::box07));
panel.add(createButton("Example 8", 150, 25, this::box08));
panel.add(createButton("Example 9", 150, 25, this::box09));

91
91
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHAA
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHAA
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE layoutand
Layout andthe
tHecomponent’s
CoMponent’ssize
sIze
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE layoutand
layout andtHe
tHeCoMponent’s
CoMponent’ssIze
sIze

panel.add(createButton("Example 10", 150, 25, this::box10));


panel.add(createButton("Example
panel.add(createButton("Example 10",
10", 150,
150, 25,
25, this::box10));
this::box10));
panel.add(createButton("Example 11", 150, 25, this::box11));
panel.add(createButton("Example
panel.add(createButton("Example 11",
11", 150,
150, 25,
25, this::box11));
this::box11));
add(panel);
add(panel);
add(panel);
}
}}

private JButton createButton(String text, int width, int height,


private JButton
private JButton createButton(String
createButton(String text,
text, int
int width,
width, int
int height,
height,
ActionListener listener)
ActionListener listener)
ActionListener listener)
{
{{
JButton cmd = new JButton(text);
JButton cmd
JButton cmd == new
new JButton(text);
JButton(text);
cmd.setPreferredSize(new Dimension(width, height));
cmd.setPreferredSize(new Dimension(width,
cmd.setPreferredSize(new Dimension(width, height));
height));
cmd.setMinimumSize(new Dimension(width, height));
cmd.setMinimumSize(new Dimension(width,
cmd.setMinimumSize(new Dimension(width, height));
height));
cmd.setMaximumSize(new Dimension(width, height));
cmd.setMaximumSize(new Dimension(width,
cmd.setMaximumSize(new Dimension(width, height));
height));
cmd.setAlignmentX(Component.CENTER_ALIGNMENT);
cmd.setAlignmentX(Component.CENTER_ALIGNMENT);
cmd.setAlignmentX(Component.CENTER_ALIGNMENT);
cmd.addActionListener(listener);
cmd.addActionListener(listener);
cmd.addActionListener(listener);
return cmd;
return cmd;
return cmd;
}
}}
}
}}

You
You
You must
Youmust
must primarily
mustprimarily
primarily note
primarilynote
note how,
notehow,
how, the
how,the method
themethod
the createWindow()
methodcreateWindow()
method defines
definesaaaaBoxLayout,
createWindow()defines
createWindow() defines BoxLayout, and
BoxLayout,and
BoxLayout, how
andhow
and that
howthat
how that
that

BoxLayout.Y_AXIS
BoxLayout.Y_AXIS
BoxLayout.Y_AXIS

indicates
indicates
indicates that
indicatesthat
thatthe
that the
the components
thecomponents
componentsmust
components must
mustbe
must be laid
belaid
be out
laidout
laid outin
out in
inaaaacolumn.
in column. Note
column.Note
column. also
Notealso
Note that
thataaaaBoxLayout
alsothat
also that BoxLayout
BoxLayout
BoxLayout
is defined
isisisdefined
defined slightly
definedslightly
slightly differently
slightlydifferently
differently than
differentlythan
thanthe
than the
the other
theother layout
otherlayout
other managers.
layoutmanagers.
layout Furthermore,
managers.Furthermore,
managers. Furthermore,note
Furthermore, note how
notehow
note the
howthe
how the
the
method
method createButton()
createButton()
method createButton()
method defines
defines
createButton() defines the
the
defines the alignment
alignment
the alignment
alignment of of
of the
the
of the individual
individual
the individual components:
components:
individual components:
components:

cmd.setAlignmentX(Component.CENTER_ALIGNMENT);
cmd.setAlignmentX(Component.CENTER_ALIGNMENT);
cmd.setAlignmentX(Component.CENTER_ALIGNMENT);

that
that
that means
meansaaaahorizontal
thatmeans
means horizontal
horizontal alignment.
horizontalalignment.
alignment.The
alignment. The parameter
parameterisisis
Theparameter
The parameter isaaaaconstant
constant
constantof
constant of the
ofthe
of type
thetype
the float
typefloat
type and
floatand
float has
hasaaaa
andhas
and has
value
value
value between
between000
valuebetween
between and
0and
and1.
and 1.
1. The
1.The
The value
Thevalue
value indicated
valueindicated
indicatedthe
indicated the degree
thedegree
the degreeto
degree to which
towhich
to the
whichthe
which component
thecomponent
the componentmust
component must
mustbe
must bebe
be
aligned
aligned
aligned from
alignedfrom
from left
fromleft
leftto
left to
to right,
toright,
right,and
right, and there
andthere
and is defined
thereisisisdefined
there the
definedthe
defined following
thefollowing
the constants:
followingconstants:
following constants:
constants:

000
0=== Component.LEFT_ALIGNMENT
=Component.LEFT_ALIGNMENT
Component.LEFT_ALIGNMENT
Component.LEFT_ALIGNMENT
0.5
0.5 = Component.CENTER_ALIGNMENT
0.5 ==Component.CENTER_ALIGNMENT
0.5 = Component.CENTER_ALIGNMENT
Component.CENTER_ALIGNMENT
1 = Component.RIGHT_ALIGNMENT
111===Component.RIGHT_ALIGNMENT
Component.RIGHT_ALIGNMENT
Component.RIGHT_ALIGNMENT

IfIfIf
Ifyouyou
you open
youopen
open Example
Example111
openExample
Example you
1you
you get
youget
get the
getthe window
thewindow
the windowshown
window shown below.
shownbelow.
shown The
below.The
below. window
Thewindow
The windowshows
window shows three
showsthree
shows JLabel
threeJLabel
three JLabel
JLabel
components
components
components that
components that
that are
are
that are laid
laid
are laid out
out
laid out in
in
out in a a column
column
in aa column
column bybyby a a BoxLayout.
BoxLayout.
by aa BoxLayout. When
When
BoxLayout. When
When you you
you test
test
you test this
this
test this example,
example,
this example,
example,
you
youyou
youneed need
needto
need to
to observe
toobserve
observe what
observewhat
what happens
whathappens
happensto
happens to the
tothe
to components
thecomponents
the componentswhen
components when
whenthe
when the window
thewindow
the is resized.
windowisisisresized.
window The
resized.The
resized. The
The
components
components
components changes
components changes
changes to
changes to to their
their
to their maximum
maximum
their maximum
maximum size size
size and
and
size and are
are
and are compressed
compressed
are compressed
compressed to to
to their
their
to their minimum
minimum
their minimum size,
size,
minimum size,size,
and
andand finally
finally
and finally you
you
finally you should
should
you should note
note
should note that
that
note that they
they
that they are
are
they are adjusted
adjusted
are adjusted with
with
adjusted with the
the
with the left
left
the left edge.
edge.
left edge.
edge.

92
9292
92
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

93
JAVA 2:
JAVA 2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL USER
GRAPHICAL USER INTERFACE
INTERFACE Layout and
layout and tHe
the CoMponent’s
component’s sIze
size

The code
The code is
is as
as follows,
follows, which
which requires
requires no
no further
further explanation:
explanation:

package layoutpanels;

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class Box01View extends JDialog


{
public Box01View()
{
super(null, "BoxLayout", Dialog.ModalityType.MODELESS);
setSize(400, 400);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
}

private void createWindow()


{
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.add(createLabel(100, 50, Color.red));
panel.add(createLabel(150, 75, Color.green));
panel.add(createLabel(200, 100, Color.blue));
add(panel);
}

private JLabel createLabel(int width, int height, Color color)


{
JLabel label = new JLabel();
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setOpaque(true);
label.setBackground(color);
label.setPreferredSize(new Dimension(width, height));
label.setMinimumSize(new Dimension(width / 2, height / 2));
label.setMaximumSize(new Dimension(width * 2, height * 2));
return label;
}
}

94
94
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

The following 9 examples are substantially identical to the above, and shows the same three
The following 9 examples are substantially identical to the above, and shows the same three
components. The difference is how the components are adjusted, and whether they are laid
components. The difference is how the components are adjusted, and whether they are laid
out vertically or horizontally. I will not show these examples here, but you should open the
out vertically or horizontally. I will not show these examples here, but you should open the
dialog boxes to see what is happening.
dialog boxes to see what is happening.

Generally a BoxLayout does not inserts gaps between the components, but it is possible to
Generally a BoxLayout does not inserts gaps between the components, but it is possible to
add no visual components, and I will as an example to explain Example 10. If you opens
add no visual components, and I will as an example to explain Example 10. If you opens
the dialog box, you get the following window:
the dialog box, you get the following window:

where the components this time is laid out horizontally. Between the first two components,
where the components this time is laid out horizontally. Between the first two components,
has been added an invisible component of width 10, while there between the two last
has been added an invisible component of width 10, while there between the two last
components is inserted a gap that fills the part of the panel that are not used. The components
components is inserted a gap that fills the part of the panel that are not used. The components
height is as previously limited by their maximum height, and the width is their preferred
height is as previously limited by their maximum height, and the width is their preferred
width. The code is as follows:
width. The code is as follows:

package layoutpaneler;

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class Box10View extends JDialog


{
public Box10View()
{
super(null, "BoxLayout", Dialog.ModalityType.MODELESS);
setSize(600, 200);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
}

95
95
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHA A
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE Layoutand
layout andtHe
theCoMponent’s
component’ssIze
size

private void createWindow()


{
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.add(createLabel(100, 50, Color.red));
panel.add(Box.createRigidArea(new Dimension(10, 0)));
panel.add(createLabel(150, 75, Color.green));
panel.add(Box.createHorizontalGlue());
panel.add(createLabel(200, 100, Color.blue));
add(panel);
}

private JLabel createLabel(int width, int height, Color color)


{
JLabel label = new JLabel();
label.setAlignmentY(Component.TOP_ALIGNMENT);
label.setOpaque(true);
label.setBackground(color);
label.setPreferredSize(new Dimension(width, height));
label.setMinimumSize(new Dimension(width / 2, height / 2));

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

9696
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

label.setMaximumSize(new Dimension(width * 2, height * 2));


return label;
}
}

which
whichisisalmost
almostidentical
identicaltotothe
theprevious
previousexample,
example,but
butyou
youshould
shouldnote
notehow
howthe
thecreateWindow()
createWindow()
inserts
inserts spaces between the components. The important thing about this exampleisisthat
spaces between the components. The important thing about this example thatthe
the
blue
bluelabel
labelfollows
followsthe
thewindow’s
window’sright
rightedge.
edge.

Finally,
Finally,the
thelast
lastexample
example(Example
(Example11),
11),which
whichopens
opensthe
thefollowing
followingdialog
dialogbox:
box:

The
Thewindow
windowplaces
placesthree
threecomponents
componentswith
withaaBoxLayout:
BoxLayout:

1.
1.aaJLabel
JLabel
2.
2. a JScrollPanewith
a JScrollPane withaalist
listbox
box
3.
3.aaJPanel
JPanelwith
withtwo
twobuttons
buttons

You
Youshould
shouldstudy
studythe
thecode
codeand
andsee
seewhat
whathappens
happenswhen
whenthe
thewindow
windowisisresized.
resized.

EXERCISE
EXERCISE88
You
Youmust
mustwrite
writeaaprogram
programthat
thatyou
youcan
cancall
callBoxes.
Boxes.The
Theprogram
programshould
shouldopen
openaawindow
windowasas
shown
shownbelow,
below,that
thatshows
shows12
12JLabel
JLabelcomponents
componentsinindifferent
differentcolors.
colors.The
Theprogram
programdodonot
not
perform anything and there should be no event handling.
perform anything and there should be no event handling.

97
97
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

The
The design
design isis aa panel
panel with
with aa BoxLayout
BoxLayout that
that containts
containts two
two other
other panels
panels with
with aa BoxLayout
BoxLayout
(a left and a right). In addition, apply the following
(a left and a right). In addition, apply the following

--- The
The components
components must
must have
have aa fixed
fixed size.
size.
--- Vertical
Vertical between the components there must
between the components there must be
be aa gap
gap of
of 5.
5.
--- When
When the window is resized, the 6 components to the right mustfollow
the window is resized, the 6 components to the right must followthe
thewindow’s
window’s
right
right edge, while the 6 lower components must follow the window’s bottom edge.
edge, while the 6 lower components must follow the window’s bottom edge.

6.7
6.7 NULL
NULL LAYOUT
LAYOUT
Above
Above II have
have mentioned
mentioned the
the most
most important
important of
of Java’s
Java’s layout
layout managers,
managers, but
but itit isis actually
actually
possible
possible to place components in a window without using a layout manager. If, in
to place components in a window without using a layout manager. If, in the
the
demo
demo program you clicks the button Null layout, you get the following dialog, that has six
program you clicks the button Null layout, you get the following dialog, that has six
components (the buttons have no function)
components (the buttons have no function)

package layoutpanels;

import java.awt.*;
import javax.swing.*;

98
98
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Layout and the component’s size
GRAPHICAL USER INTERFACE layout and tHe CoMponent’s sIze

public class NulllayoutView extends JDialog


{
public NulllayoutView()
{
super(null, "Null Layout", Dialog.ModalityType.MODELESS);
setSize(340, 200);
setResizable(false);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
createWindow();
setVisible(true);
}

private void createWindow()


{
setLayout(null);
addComponent(this, new JLabel("Zip code"), 20, 20, 100, 20);
addComponent(this, new JLabel("Town"), 20, 60, 100, 20);
addComponent(this, new JTextField(), 100, 20, 50, 20);
addComponent(this, new JTextField(), 100, 60, 220, 20);
addComponent(this, new JButton("Cancel"), 230, 110, 90, 24);
addComponent(this, new JButton("OK"), 120, 110, 90, 24);
}

99
99
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Layout
layoutand
andthe
tHecomponent’s
CoMponent’ssize
sIze

private void addComponent(Container container, Component component,


int left, int top, int width, int height)
{
component.setBounds(left, top, width, height);
container.add(component);
}
}

Thefirst
The firststatement
statementinincreateWindow()
createWindow()setssetsthe
thelayout
layoutmanager
managertotonull,
null,which
whichmeans
meansthethewindow
window
hasno
has nolayout
layoutmanager.
manager.Then
Thenthethemethod
methodaddsaddscomponents
componentsusing usingthe
themethod
methodaddComponent().
addComponent().
ItItdefines
definesthethecomponents
componentssize sizeand
andlocation
locationwith
withthe
themethod
methodsetBounds()
setBounds()where
wherethethetwo
twofirst
first
parametersare
parameters arethe
theupper
upperleft
leftcorner
cornerofofthe
thecomponent’s
component’slocation
locationininthe
thepanel,
panel,while
whilethe
thetwo
two
lastparameters
last parametersare arethe
thewidth
widthand andheight.
height.That
Thatis,is,the
thecomponent
componentisisassigned
assignedan anabsolute
absolute
positionand
position andsize.
size.These
Thesevalues
valuescan
canalso
alsobebeassigned
assignedwithwithsetLocation()
setLocation()and
andsetSize().
setSize().

Immediatelyabove
Immediately aboveworks
workssimple,
simple,but
butiningeneral
generalititisisadvisable
advisabletotouse
useaalayout
layoutmanager,
manager,asas
thecomponent’s
the component’ssizes
sizescan
caninvolve
involvefor
forexample
examplethe
thecurrent
currentfont.
font.IfIfyou
youuse
useaaparticular
particularfont,
font,
andthe
and thewindow
windowsize
sizedoes
doesnot
notchange
change(note
(notethat
thatthis
thisisisnot
notpossible
possibleininthe
theabove
aboveexample),
example),
theuse
the useofofcomponents
componentsatatfixed
fixedpositions,
positions,however
howeverisisaapossibility.
possibility.

PROBLEM11
PROBLEM
Youmust
You mustwrite
writeaaprogram
programthatthatisisaaloan
loancalculation
calculationprogram
programandandthus
thusaaprogram
programwhere
wherethethe
usercan
user canenter
enterthetheamount
amountofofaaloan,
loan,the
theinterest
interestrate
rateand
andnumber
numberofofperidos.
peridos.The
Theprogram
program
shouldthen
should thencalculate
calculatethe
thepayment
paymentwhen whenthe theloan
loanisisan
anannuity.
annuity.ItItshould
shouldbebementioned
mentioned
thatthere
that thereare
aremany
manysuch
suchprograms
programson onthe
theInternet
Internetthat
thatyou
youcancancompare
comparethetheresult
resultwith.
with.
Anannuity
An annuityisisaaloan
loanthat
thatisisamortized
amortizedwithwithaafixed
fixedpayment
paymenteach
eachperiod.
period.AApayment
paymentconsist
consist
ofofinterest
interestand
andrepayment
repaymentand andininthe
thebeginning
beginningisisaabig
bigpart
partofofthe
thepayment
paymentinterest
interestand
andaa
smallerpart
smaller partisisrepayment.
repayment.This Thissituation
situationisischanging
changingcontinuously,
continuously,sosothat
thattowards
towardsthetheend
end
ofofthe
theloan
loanperiod,
period,thethelargest
largestpart
partofofthe
thepayment
paymentisisrepayment.
repayment.IfIf

--- GG==thetheloan
loan
--- yy==the
thepayment
payment
--- nn==number
numberofofperiods
periods
--- r r==interest
interestrate
rate

100
100
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

the relationship between the loan and the payment is given by the following formula:

This formula assumes that the interest rate is constant throughout the loan period and the
first payment must take place 1 period after you got the loan, and you should assume that
these assumptions apply. The following formula determines the outstanding debt immediately
after the kth payment is paid:

The program must open a window where the user must enter:

-- cost of loan formation


-- the size of the loan
-- the interest rate in percent pro ano
-- the repayment period in years
-- number of periods a year

Using this information, the program must calculate the payment. In addition, it should
be possible to open a window that shows an amortization, and thus an overview of the
loan that for each period shows the payment, the interest, the repayment and the debt
outstanding after this date.

6.8 MVC
When you study my solution of the above problem, primarily focusing on the program’s
architecture and the classes that are used. The program can be written differently – and
simpler – but the chosen architecture is a step toward a design pattern for a GUI program
that is called for MVC for Model View Controller. In the book Java 7 I will return to this
pattern, and although the pattern is first treated in this book, I will already start to use it. The
pattern is very simple and means to develop a GUI program with a three-layer architecture

101
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Layout and the component’s size

where the model consists of the classes that defines the program’s data and state, while
controller layer has classes who mainly perform control of entries etc. and optionally also
has essential calculation functions (business logic). Finally, the view layer has all the classes
for the user interface and thus for windows and dialogs.

The goal of the pattern is to separate the code so that the code regarding the program’s data
are placed in classes in the model and code used for data control and logical operations
are placed in the control layer, whereas the view layer alone must contain the code which
has to do with the visual representation and user interaction. Conforms to the pattern you
get a code which might be a bit bigger, but in return is far easier to read and understand.

I will in the following books when there is slightly larger programs begin using the pattern,
and so far it is only a question of the division of the program’s classes in logical layers,
and although it does not sound like much, the pattern has proved very appropriate as
architecture for a GUI program. Therefore, I would in a small way begin using the pattern
only as a way to a reasonable division of the code. There is much more to say about MVC,
and including how each layer should communicate with the others, and there may also be
several layers, but the details I’ll defer to the book Java 7.

102
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Paedit
paedIt

7 PAEDIT
7 PAEDIT
In
In this
this chapter
chapter II will
will show
show aa program
program that
that is
is aa simple
simple text
text editor
editor and
and thus
thus aa program
program where
where
the
the user
user can
can enter
enter text
text and
and save
save the
the text
text in
in aa file.
file. The
The program
program is is relatively
relatively simple
simple and
and has
has
only
only aa single
single window.
window. TheThe layout
layout is
is solved
solved with
with aa single
single BorderLayout,
BorderLayout, and and concerning
concerning GUI
GUI
programs
programs thethe program
program mainly
mainly shows
shows the
the following:
following:

--- how
how to
to create
create and
and use
use aa menu
menu
--- how
how to
to create
create and
and use
use aa toolbar
toolbar
--- how
how to
to use
use aa JTextArea
JTextArea component
component
--- how
how to
to use
use finished
finished dialog
dialog boxes
boxes from
from the
the Swing
Swing API
API
--- how
how to
to use
use the
the clipboard
clipboard

Regarding
Regarding point
point 44 II have
have previously
previously shown
shown the
the use
use of
of JOptionPane.showMessageDialog(),
JOptionPane.showMessageDialog(), but but
the
the class
class JOptionPane
JOptionPane has has other
other dialog
dialog boxes
boxes that
that II will
will use.
use. Moreover,
Moreover, II shows
shows the
the use
use of
of
the
the class
class JFileChooser
JFileChooser that
that implements
implements aa dialog
dialog box
box for
for browsing
browsing the
the file
file system.
system.

The
The program
program requires
requires that
that you
you can
can read
read and
and write
write aa text
text file,
file, and
and inin the
the book
book Java
Java 11 II
explained
explained how
how to
to do
do that.
that. In
In fact,
fact, the
the program
program does
does not
not very
very much
much concerning
concerning algorithms
algorithms
and
and thus
thus problem
problem solving,
solving, so
so most
most of of the
the program
program deals
deals with
with howhow toto write
write text
text to
to aa file
file
and
and read
read text
text from
from aa file,
file, and
and it’s
it’s something
something you you just
just have
have to to take
take note
note of,
of, but
but behind
behind itit
all,
all, there
there are
are many
many details
details that
that II first
first are
are able
able to
to explain
explain atat aa later
later time.
time.

Similar
Similar to
to what
what is
is said
said above,
above, the
the program
program has
has aa very
very simple
simple architecture,
architecture, consisting
consisting of
of aa
view
view and
and aa model,
model, and
and by
by far
far most
most of
of the
the program’s
program’s code
code is
is in
in the
the view.
view. The
The program
program has
has
aa 2-tier
2-tier architecture.
architecture.

7.1
7.1 THE
THE MODEL
MODEL
The
The model
model consists
consists only
only of
of aa single
single class,
class, called
called Document,
Document, which
which encapsulates
encapsulates aa text
text file,
file,
and
and thus
thus represents
represents the
the document
document that
that the
the program
program must
must be
be able
able to
to edit.
edit. The
The class
class is
is written
written
as
as follows:
follows:

package paedit;

import java.io.*;

public class Document


{
private String text; // the documents text
private File file; // object that represents the document's file

103
103
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Paedit
GRAPHICAL USER INTERFACE paedIt

public Document()
{
text = "";
file = null;
}

public Document(File file) throws Exception


{
BufferedReader reader = null;
try
{
StringBuilder builder = new StringBuilder();
reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
builder.append(line);
builder.append("\n");
}
text = builder.toString();
this.file = file;
}
catch (Exception ex)
{
text = "";
this.file = null;
throw new Exception("The content of the file could not be read");
}
finally
{
if (reader != null) reader.close();
}
}

public String getText()


{
return text;
}

public void setText(String text)


{
this.text = text;
}
public boolean save()
{
if (file == null) return false; else return save(file);
}

104
104
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHA A
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE Paedit
paedIt

public boolean save(File file)


{
BufferedWriter writer = null;
try
{
writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
this.file = file;
return true;
}
catch (Exception ex)
{
return false;
}
finally
{
if (writer != null)
try
{
writer.close();
}

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

105
105
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Paedit
GRAPHICAL USER INTERFACE paedIt

catch (Exception ex)


{
}
}
}
}

There are two variables, the first being for the text, while the other represents a file, and is
a File object that represents a file path.

The default constructor creates a blank document, not yet saved and associated with a file.
The other constructor has a parameter that is a File object, and the constructor trys to read
the contents of this file as a text. Most methods concerning files can raise exceptions, as
there may be many reasons why a particular file operation can not be performed properly.
As an example it may be that the file does not exist, or that you may not have the right to
open it. Therefore, statements regarding files almost always are placed in try/catch blocks.
In this case raises the constructor an exception if the content of the file for one reason or
another can not be read. A text file can be read with a BufferedReader, an object that reads
the file line by line. As the lines are reading the are added to a StringBuilder, which is used
to build up the document. If an error occurs, the constructor go to the catch block, and
the result is again a blank document.

The method save() trys to save the content (the document) in a file, but this is only possible if
the variable file refers to a file. If it does not, the method returns false. Otherwise the method
calls another save() method but with a File as a parameter. It looks like the constructor,
and you write the text to a file using a BufferedWriter. The text is saved with the method
write(), that saves all the text as a whole and also all the line breaks.

Note that the class also has get and set methods for variable text, such the program’s view
can read the text and update it again.

7.2 THE VIEW


7.2
The program’s view layer has two classes that is the class MainView and a class Tools. The
last is a simple class that contains a few tools that can also be interested in other programs.
If you executes the program, it opens a window as shown below, where there at the top is
a menu and a toolbar and in the bottom a status line (is empty when the program starts).
Center is a JTextArea component, that is an input field like a JTextField, but a field where
you can enter more lines.

106
106
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH AA
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Paedit
paedIt

THE
THE CLASS
CLASS TOOLS
TOOLS
The
The program
program has
has aa class
class Tools
Tools that
that has
has only
only static
static members,
members, which
which means
means that
that the
the members
members
can be refered without an object of the type
can be refered without an object of the type Tools: Tools:

package paedit;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Tools


{
public static Font defFont = new Font("Liberation Sans", Font.PLAIN, 14);
public static Font txtFont = new Font("FreeMono", Font.PLAIN, 16);

public static Color statusLine = new Color(240, 240, 240);

public static ImageIcon createImageIcon(String path, int width)


{
java.net.URL imgURL = Tools.class.getResource(path);
if (imgURL != null) return new ImageIcon(
new ImageIcon(imgURL, "").getImage().getScaledInstance(
width, width, Image.SCALE_SMOOTH), "");
return null;
}

107
107
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Paedit
GRAPHICAL USER INTERFACE paedIt

public static JButton createCommand(Icon icon, String toolTip,


ActionListener listener)
{
JButton cmd = new JButton();
cmd.setFont(defFont);
cmd.setIcon(icon);
cmd.setMargin(new Insets(0, 0, 0, 0));
cmd.setToolTipText(toolTip);
cmd.addActionListener(listener);
return cmd;
}
}

Initially are defined three constants where the first two defines the font to respectively
default and buttons. The third defines the color of the status bar. In many contexts you
must desire to control the fonts and colors, a window must apply, and it is recommended
to define that kind of values as constants, as shown above, since in this way you can easily
change the values, and as such you can also use them in multiple windows.

108
108
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Paedit
GRAPHICAL USER INTERFACE paedIt

The class also has two methods, which are difficult to understand (again because you still
The class also has two methods, which are difficult to understand (again because you still
lack many Java details), so you should largely accept them as they are. The first is used to
lack many Java details), so you should largely accept them as they are. The first is used to
load an icon from the application’s jar file. The two parameters are the image name and
load an icon from the application’s jar file. The two parameters are the image name and
the icon size. The first statement defines a reference to the image in the jar file, while the
the icon size. The first statement defines a reference to the image in the jar file, while the
next statement creates an icon and scale it to the desired size. The last method creates a
next statement creates an icon and scale it to the desired size. The last method creates a
button with an icon and associate an event handler for the button. In addition a tooltip
button with an icon and associate an event handler for the button. In addition a tooltip
is added to the button.
is added to the button.

THE MENU
THE MENU
It is easy to add a menu to a window. A menu is basically just a collection of buttons, just
It is easy to add a menu to a window. A menu is basically just a collection of buttons, just
shown in a different way as a menu item, but the effect is the same, that you can click on
shown in a different way as a menu item, but the effect is the same, that you can click on
a menu item and the item sends an ActionEvent. The menu must be defined, and it can fill
a menu item and the item sends an ActionEvent. The menu must be defined, and it can fill
a lot, but below shows how the menu is defined i MainView in this case:
a lot, but below shows how the menu is defined i MainView in this case:

private void createMenu()


{
JMenuBar menuBar = new JMenuBar();
menuBar.add(createFileMenu());
menuBar.add(createEditMenu());
setJMenuBar(menuBar);
}

private JMenu createFileMenu()


{
JMenu menu = new JMenu("Files");
menu.add(createMenuItem("New document", this::blank));
menu.add(createMenuItem("Open document", this::open));
menu.add(createMenuItem("Savve document", this::save));
menu.add(createMenuItem("Save document as", this::saveas));
menu.addSeparator();
menu.add(createMenuItem("Exit", this::close));
return menu;
}

private JMenu createEditMenu()


{
JMenu menu = new JMenu("Edit");
menu.add(createMenuItem("Copy", this::copy));
menu.add(createMenuItem("Paste", this::paste));
menu.add(createMenuItem("Cut", this::cut));
menu.addSeparator();
menu.add(createMenuItem("Search", this::search));
return menu;
}

109
109
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
JAVA 2: PROGRAMS WITH A
GRAPHICAL
GRAPHICALUSER
USERINTERFACE
INTERFACE Paedit
paedIt
GRAPHICAL USER INTERFACE paedIt

private
private JMenuItem
JMenuItem createMenuItem(String
createMenuItem(String text,
text, ActionListener
ActionListener listener)
listener)
{{
JMenuItem
JMenuItem item
item == new
new JMenuItem(text);
JMenuItem(text);
item.addActionListener(listener);
item.addActionListener(listener);
return
return item;
item;
}}

InIn principle,
Inprinciple,
principle,the the code
codeisis
thecode quite
isquite simple
quitesimple
simpleand and easy
easyofof
andeasy understand.
ofunderstand.
understand.There There
Thereareare three
arethree components.
threecomponents.
components.
The
The menu is a JMenuBar which is a component, that contains
The menu is a JMenuBar which is a component, that contains the menu and canbe
menu is a JMenuBar which is a component, that contains the
the menu
menu and
and can
can be added
beadded
added
to the
totothe window
thewindow
windowand and automatically
andautomatically is
automaticallyisisplaced placed at
placedatatthe the
thetoptop of
topofofthethe window.
thewindow.
window.The The JMenuBar
JMenuBarisis
TheJMenuBar is
added
added to the
addedtotothe window
thewindow
windowwith with
withthethe method
themethod setJMenuBar().
methodsetJMenuBar().
setJMenuBar().The The second
Thesecond component
secondcomponent is
componentisisJMenu JMenu
JMenu
and
and represents
represents a a menu,
menu, while
while the
the last
last isis JMenuItem
JMenuItem and
and represents
represents a
and represents a menu, while the last is JMenuItem and represents a menu item. You shoulda menu
menu item.
item. You
You should
should
note
note that
notethat you
thatyou assign
assignaaalistener
youassign listener
listenerinin quite
inquite
quitethethe same
thesame
samewayway
wayyou you assign
assignaaalistener
youassign listener
listenertototoaaabutton.
button. The
button.The
The
individual
individual event
individualevent handlers
eventhandlers
handlersareare written
arewritten at
writtenatatthethe end
theend of
endofofthethe class.
theclass.
class.

THE
THE TOOLBAR
THETOOLBAR
TOOLBAR
The
The program’s
Theprogram’s window
program’swindow
windowhashas
hasaaatoolbar
toolbar that
thatisis
toolbarthat merely
merelyaaacontainer
ismerely container that
containerthat can
thatcan contains
cancontains components.
containscomponents.
components.
InIn this case, there are four buttons, but the buttons are this time not represented
In this case, there are four buttons, but the buttons are this time not representedby
this case, there are four buttons, but the buttons are this time not represented by
byaaatext,
text,
text,
but
but an
an image.
image.
but an image.

Each
Eachofof
Each these
ofthese controls
thesecontrols include
controlsinclude
includeanan image
animage (an
image(an icon),
(anicon), which
icon),which
whichmustmust
mustbebe available
beavailable for
availablefor the
forthe
the
program.
program. This
This can
can be
be done
done in
in several
several ways,
ways, but
but if,
if, as
as here
here itit are
are small
small icons,
icons, you
you
program. This can be done in several ways, but if, as here it are small icons, you can use can
can use
use
the
the following
thefollowing procedure:
followingprocedure:
procedure:

1.
1. add
1.add package
packagetoto
addpackage the
tothe NetBeans
theNetBeans project
project–––inin
NetBeansproject this
inthis case
caseitititisis
thiscase isaaasub
sub package
packagetoto
subpackage paedit
topaedit
paedit
called
called images,
images, and
and after
after you
you creates
creates the
the package
package the
the name
name
called images, and after you creates the package the name is paedit.images is
is paedit.images
paedit.images
2.
2. copy
2. copythe
copy the images
imagestoto
theimages the
tothe corresponding
thecorresponding folder
correspondingfolder (the
folder(the folder
(thefolder
folderimagesimages has
hasinin
imageshas this
inthis case
caseisis
thiscase is
4 png
44png files)
pngfiles)
files)

The
The advantage
advantageofof
Theadvantage this
ofthis method
methodisis
thismethod that
isthat the
thatthe icons
theicons are
iconsare packed
arepacked together
packedtogether with
togetherwith the
withthe class
theclass files
filesinin
classfiles in
the
the project’s
project’s jar
jar file.
file.
the project’s jar file.

Then
Then there
thereisis
Thenthere the
isthe toolbar,
thetoolbar, which
whichisis
toolbar,which defined
definedasas
isdefined follows:
asfollows:
follows:

private
private JToolBar
JToolBar createToolbar()
createToolbar()
{{
JToolBar
JToolBar toolBar
toolBar == new
new JToolBar();
JToolBar();
toolBar.setBackground(Tools.statusLine);
toolBar.setBackground(Tools.statusLine);
toolBar.add(Tools.createCommand(
toolBar.add(Tools.createCommand(
Tools.createImageIcon("/paedit/images/copy.png",
Tools.createImageIcon("/paedit/images/copy.png", 26),
26),
"Copy
"Copy text
text to
to the
the clip
clip board",
board", this::copy
this::copy ));
));
toolBar.addSeparator(new
toolBar.addSeparator(new Dimension(10,
Dimension(10, 10));
10));

110
110
110
JAVA 2:
JAVA 2: PROGRAMS
PROGRAMS WITH
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Paedit
paedIt

toolBar.add(Tools.createCommand(
Tools.createImageIcon("/paedit/images/paste.png", 26),
"Insert text from the clip board", this::paste ));
toolBar.addSeparator(new Dimension(10, 10));
toolBar.add(Tools.createCommand(
Tools.createImageIcon("/paedit/images/cut.png", 26),
"Delete text and copy the text to the clip board", this::cut ));
toolBar.addSeparator(new Dimension(20, 20));
toolBar.add(Tools.createCommand(
Tools.createImageIcon("/paedit/images/search.png", 26),
"Search the document", this::search ));
toolBar.setPreferredSize(new Dimension(0, 36));
return toolBar;
}

Here I am using the methods from the Tools class and you should primarily notice how one
refers to the individual images. An image is a resource in the application’s jar file, and you
must specify the path leading to the current image, the path is relative to the project. Note
also the use of the same event handlers as used in the menu. The class JTextArea supports
also copy/paste, so there is actually not really need for the buttons, but they are included
because the goal is to show how to create a toolbar. In this case includes the toolbar buttons,
but it may contain any other components.

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

111
111
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH A
A
JAVA2:2:PROGRAMS
GRAPHICALPROGRAMS
USER WITHAA
JAVA
GRAPHICAL USER INTERFACE
JAVA 2: PROGRAMS WITH
INTERFACE
WITH A paedIt
paedIt
GRAPHICALUSER
GRAPHICAL USER INTERFACE paedIt
GRAPHICAL USERINTERFACE
INTERFACE Paedit
paedIt

THE STATUS LINE


THE
THE STATUS
THESTATUS LINE
STATUSLINE
LINE
It is actually not a real status bar, but just a JLabel which can display a left-aligned text:
ItIt
Itisis actually
isactually not
nota aareal
actuallynot real status
realstatus bar,
statusbar, but
bar,but just
justa aaJLabel
butjust JLabel which
JLabelwhich can
whichcan display
displaya aaleft-aligned
candisplay left-aligned text:
left-alignedtext:
text:
private JLabel createStatus()
private JLabel createStatus()
private JLabel createStatus()
{
{
{ JLabel label = new JLabel();
JLabel label = new JLabel();
JLabel label = new JLabel();
label.setFont(Tools.defFont);
label.setFont(Tools.defFont);
label.setFont(Tools.defFont);
label.setOpaque(false);
label.setOpaque(false);
label.setOpaque(false);
label.setBackground(Tools.statusLine);
label.setBackground(Tools.statusLine);
label.setBackground(Tools.statusLine);
label.setHorizontalAlignment(JLabel.LEFT);
label.setHorizontalAlignment(JLabel.LEFT);
label.setHorizontalAlignment(JLabel.LEFT);
label.setPreferredSize(new Dimension(0, 25));
label.setPreferredSize(new Dimension(0, 25));
label.setPreferredSize(new
return label; Dimension(0, 25));
return label;
} return label;
}
}
Assignwith
Assign withthe
thelabel
labelisisa amethod
methodthat
thatisisused
usedtotoupdate
updatethe
thetext:
text:
Assign
Assign with
with the
the label
label is
is aa method
method that
that is
is used
used to
to update
update the
the text:
text:
private void setStatus()
private void setStatus()
private
{ void setStatus()
{
{ status.setText(String.format("%d linje, %d tegn",
status.setText(String.format("%d linje, %d tegn",
status.setText(String.format("%d linje, %d tegn", 1));
txtDoc.getLineCount(), txtDoc.getText().length()+
txtDoc.getLineCount(), txtDoc.getText().length()+ 1));
} txtDoc.getLineCount(), txtDoc.getText().length()+ 1));
}
}
ItItrefers
referstotothe
theJTextArea
JTextAreacomponent
componentcalled
calledtxtDoc,
txtDoc,andandthethestatus
statusline
lineshows
showsthe
thenumber
number
It refers to the JTextArea component called txtDoc, and the
the status line shows the number
status line shows the
ofIt refers
oflines to the
linesand
and JTextArea
thenumber component
numberofof characters called
charactersentered txtDoc,
entered theand
ininthe field.
field. number
of lines and the number of characters entered in the
of lines and the number of characters entered in the field. field.
THE
THELAYOUT
LAYOUT
THE
THE LAYOUT
LAYOUT
MainView
MainViewdefines
definesfour
fourinstance
instancevariables:
variables:
MainView
MainView defines four instance variables:
defines four instance variables:
private JTextArea txtDoc = new JTextArea();
private JTextArea txtDoc = new JTextArea();
private JTextArea
JLabel txtDoc = new JTextArea();
status;
private JLabel status;
private JLabel status;
Document doc = new Document();
private Document doc = new Document();
private Document changed
boolean doc = new Document();
= false;
private boolean changed = false;
private boolean changed = false;
The
Thefirst
firstisisthe
theJTextArea
JTextAreacomponent
componentwhich whichisisa acomponent,
component,where
whereone
onecan canenter
enterand
andedit
edit
The
any
The first
number is the
of JTextArea
lines of component
text, and thus which
an is a component,
arbitrary document. where
The one
next can
is a enter
JLabeland
to edit
the
any number of lines of text, and thus an arbitrary document. The next is a JLabel to edit
first is the JTextArea component which is a component, where one can enter and the
any
status
any number
line, andof lines
the of
third text,
is and
the thus
Document an arbitrary
and thendocument.
the model.The next
The lastis aa JLabel
keeps to
track the
of
status line, and the third is the Document and then the model. The last keeps trackthe
number of lines of text, and thus an arbitrary document. The next is JLabel to of
status
whether
status line,
the
line, and the
document
and the third
is
third is the
changed.
is the Document
Document and
and then
then the
the model.
model. The
The last
last keeps
keeps track
track of
of
whether the document is changed.
whether the document
whether the document is changed. is changed.
The
Themethod
methodcreateWindow()
createWindow()isissimilar
similartotothe
theprevious
previousexamples,
examples,and
anddefines
definesthe
thewindow’s
window’sdesign:
design:
The
The method createWindow() is similar to the previous examples, and defines the window’s
method createWindow() is similar to the previous examples, and defines the window’s design:
design:
private void createWindow()
private void createWindow()
private
{ void createWindow()
{
{ createMenu();
createMenu();
createMenu();
setLayout(new BorderLayout());
setLayout(new BorderLayout());
setLayout(new BorderLayout());

112
112
112
112
112
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
JAVA 2: PROGRAMS
GRAPHICAL WITH A
GRAPHICALUSER
USERINTERFACE
INTERFACE Paedit
paedIt
GRAPHICAL USER INTERFACE paedIt

JPanel panel = new JPanel(new BorderLayout());


JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(3, 3, 3, 3));
panel.setBorder(new EmptyBorder(3, 3, 3, 3));
panel.add(createToolbar(), BorderLayout.NORTH);
panel.add(createToolbar(), BorderLayout.NORTH);
panel.add(status = createStatus(), BorderLayout.SOUTH);
panel.add(status = createStatus(), BorderLayout.SOUTH);
panel.add(createField());
panel.add(createField());
add(panel);
add(panel);
txtDoc.requestFocus();
txtDoc.requestFocus();
}
}

The
Thefirst
firststatement
statementcreates
createsand
andadds
addsaamenu
menutotothe
thewindow.
window.Otherwise
Otherwiseconsists
consiststhe
thewindow
window
The first statement creates and adds a menu to the window. Otherwise consists the window
only
onlyofofaaJPanel
JPanelwith
withaaBorderLayout
BorderLayoutwhich
whichNORTH
NORTHhas hasaatoolbar,
toolbar,SOUTH
SOUTHhas hasaastatus
status
only of a JPanel with a BorderLayout which NORTH has a toolbar, SOUTH has a status
bar
bar(the
(theabove
abovelabel)
label)while
whilethe
theJTextArea
JTextAreacomponent
componentencapsulated
encapsulatedininaaJScrollPane
JScrollPanefills
fillsthe
the
bar (the above label) while the JTextArea component encapsulated in a JScrollPane fills the
rest
restofofthe
thewindow.
window.
rest of the window.

The
Thefollowing
followingmethod
methodinitializes
initializesthe
thecomponent
componenttxtDoc
txtDocwhich
whichisisthe
theeditor:
editor:
The following method initializes the component txtDoc which is the editor:

private JScrollPane createField()


private JScrollPane createField()
{
{
txtDoc.setFont(Tools.txtFont);
txtDoc.setFont(Tools.txtFont);
txtDoc.setWrapStyleWord(true);
txtDoc.setWrapStyleWord(true);
txtDoc.setLineWrap(true);
txtDoc.setLineWrap(true);
txtDoc.addKeyListener(new TextChanged());
txtDoc.addKeyListener(new TextChanged());
return new JScrollPane(txtDoc);
return new JScrollPane(txtDoc);
}
}

Themethod
The method definesthe the texttotowrap
wrap to thenext
next linewhen
when theline
line doesnot
not haveroom
room for
The methoddefines
defines thetext
text to wraptotothe
the nextline
line whenthe
the linedoes
does nothave
have roomfor for
more,and
more, andthat
thatthe
thedivision
divisionmust
mustbe bedone
doneon onword
wordboundaries.
boundaries.Finally,
Finally,there
thereisisattached
attached
more, and that the division must be done on word boundaries. Finally, there is attached
anKeyListener,
an KeyListener, aneventevent handlerthat
that is performedeach each timeaakeykey is pressed.ItItsets
sets the
an KeyListener,an an eventhandler
handler thatisisperformed
performed eachtime time a keyisispressed.
pressed. It setsthethe
variable
variable changed to true, which says that the document has changed, and then called the
variablechanged
changedtototrue,
true,which
whichsays
saysthat
thatthe
thedocument
documenthas haschanged,
changed,andandthen
thencalled
calledthe
the
method
method setStatus(), which updates the status line with the current number of lines and the
methodsetStatus(),
setStatus(),which
whichupdates
updatesthe
thestatus
statusline
linewith
withthe
thecurrent
currentnumber
numberofoflines
linesand
andthe
the
currentnumber
current numberofofcharacters:
characters:
current number of characters:

class TextChanged extends KeyAdapter


class TextChanged extends KeyAdapter
{
{
public void keyTyped(KeyEvent e)
public void keyTyped(KeyEvent e)
{
{
changed = true;
changed = true;
setStatus();
setStatus();
}
}
}
}

113
113
113
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Paedit
GRAPHICAL USER INTERFACE paedIt

The event handler is defined as a method in a class that inherits KeyAdater. When a key is
The event handler is defined as a method in a class that inherits KeyAdater. When a key is
pressed, a JTextArea raises more events, and the class KeyAdapter is a class that implements the
pressed, a JTextArea raises more events, and the class KeyAdapter is a class that implements the
interface KeyListener which defines three event handlers regarding the keyboard. KeyAdapter
interface KeyListener which defines three event handlers regarding the keyboard. KeyAdapter
implements these handlers as empty methods, and you can then write a class that overrides
implements these handlers as empty methods, and you can then write a class that overrides
these handlers that you want to use. Note that it is exactly the same principle that I used
these handlers that you want to use. Note that it is exactly the same principle that I used
in the previous program related events regarding change of the window size, and you also
in the previous program related events regarding change of the window size, and you also
used the same principle in exercise 4 to catch the event when double-click on in item in
used the same principle in exercise 4 to catch the event when double-click on in item in
a list box.
a list box.

EVENT HANDLERS
EVENT HANDLERS
Finally, there are 8 event handlers (there are 8 menu items). Below is the event handler
Finally, there are 8 event handlers (there are 8 menu items). Below is the event handler
that opens a document:
that opens a document:

private void open(ActionEvent e)


{
if (changed && JOptionPane.showConfirmDialog(this,
"The document is changed. Should document be saved?", "Warning",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) ==
JOptionPane.YES_OPTION) save();
JFileChooser fileChooser = new JFileChooser();

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

114
114
JAVA 2: PROGRAMS WITH A
JAVA 2:
JAVA 2: PROGRAMS
PROGRAMS WITH
WITH AA
GRAPHICAL USER INTERFACE Paedit
GRAPHICAL USER
GRAPHICAL USER INTERFACE
INTERFACE paedIt
paedIt

fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setDialogTitle("Open text
fileChooser.setDialogTitle("Open text document");
document");
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{{
File file
File file == fileChooser.getSelectedFile();
fileChooser.getSelectedFile();
try
try
{{
doc == new
doc new Document(file);
Document(file);
txtDoc.setText(doc.getText());
txtDoc.setText(doc.getText());
changed == false;
changed false;
}}
catch (Exception
catch (Exception ex)ex)
{{
JOptionPane.showMessageDialog(this, "The
JOptionPane.showMessageDialog(this, "The document
document could
could not
not be
be opened",
opened",
"Error message", JOptionPane.OK_OPTION);
"Error message", JOptionPane.OK_OPTION);
txtDoc.setText("");
txtDoc.setText("");
changed == false;
changed false;
}}
setStatus();
setStatus();
}}
}
}

The
Thefirst
The firststatement
first statementtests
statement testswhether
tests whetherthe
whether thecurrent
the currentdocument
current documentisisismodified.
document modified.In
modified. Inthis
In thiscase
this caseitititopens
case opensaaa
opens
popup,
popup,but
popup, butthis
but thistime
this timeit’s
time it’saaaconfirm
it’s confirmdialog,
confirm dialog,aaadialog
dialog, dialogbox
dialog boxwith
box withaaaYes
with Yesand
Yes andaaaNo
and Nobutton,
No button,and
button, and
and
the
theuser
the userwill
user willbe
will beasked
be askedifififthe
asked thedocument
the documentshould
document shouldbe
should besaved.
be saved.In
saved. Inthis
In thiscase,
this case,the
case, themethod
the methodsave()
method save()isisis
save()
called,
called,which
called, whichsaves
which savesthe
saves thedocument.
the document.Next
document. NextIIIdefined
Next definedaaaJFileChooser
defined JFileChooserwhich
JFileChooser whichopens
which opensaaadialog
opens dialogbox
dialog box
box
where
whereyou
where youcan
you canbrowse
can browsethe
browse thefile
the filesystem
file systemfor
system forthe
for thefile
the filethat
file thatyou
that youwant
you wantto
want totoopen.
open.Accepting
open. Acceptingaaafile,
Accepting file,
file,
you get
you get
you a File
get aa File object
File object representing
object representing
representing the the file’s
the file’s path,
file’s path, and
path, and the
and the object
the object is used
object isis used
used inin the
in the constructor
the constructor
constructor
ininthe
in theclass
the classDocument
class Documentto
Document toopen
to openthe
open thefile.
the file.After
file. Afterthat
After thatthe
that theinput
the inputfield
input fieldisisisinitialized
field initializedwith
initialized withthe
with thefile’s
the file’s
file’s
content.
content.You
content. Youshould
You shouldnote
should notethat
note thatthe
that thecreation
the creationof
creation ofthe
of thedocument
the documentisisisplaced
document placedin
placed inaaatry/catch,
in try/catch,as
try/catch, asthe
as the
the
constructor
constructor of
constructor of the
of the class
the class Document
class Document
Document may may raise
may raise an
raise an exception.
an exception.
exception.

The
Theevent
The eventhandler
event handlerwill
handler willpossibly
will possiblycall
possibly callthe
call themethod
the methodsave()
method save()
save()

private void
private void save()
save()
{{
doc.setText(txtDoc.getText());
doc.setText(txtDoc.getText());
if (doc.save())
if (doc.save()) changed
changed == false;
false; else
else saveas();
saveas();
}}

This
Thismethod
methodcopies
copiesthethecontents
contentsof ofthe
theinput
inputfield
fieldtotothe
themodel
modeland andask
askthe
themodel
modelto towrite
write
This method copies the contents of the input field to the model and ask the model to write
the text
the text back
text back to
back to the
to the file
the file using
file using the
using the model’s
the model’s save()
model’s save() method.
save() method. Is it not
method. IsIs itit not possible
not possible (because
(becauseitititisisis
possible (because
the
aanew
newdocument
documentthat thathashasnot
notbeen
beensaved)
saved)the themethod
methodcalls callssaveas(),
saveas(),where
wherethe theuser
useragain
again
a new document that has not been saved) the method calls saveas(), where the user again
using a JFileChooser
using aa JFileChooser object
JFileChooser object will
object will be
will be able
be able to
able to browse
to browse
browse thethe file
the file system
file system and
system and enter
and enter a file
enter aa file name.
file name.
name.
using

115
115
115
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Paedit
GRAPHICAL USER INTERFACE paedIt

The event handlers to Save, Saveas and New Document works in principle the same way,
The event handlers to Save, Saveas and New Document works in principle the same way,
and I will not show the code here.
and I will not show the code here.

Then there are the three event handlers regarding the clipboard. Below is the handler that
Then there are the three event handlers regarding the clipboard. Below is the handler that
copies text to the clipboard:
copies text to the clipboard:

private void copy(ActionEvent e)


{
try
{
String text = txtDoc.getSelectedText();
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(new StringSelection(text), null);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(this,
"Text could not be copied to the clipboard",
"Error message", JOptionPane.OK_OPTION);
}
}

Firstthe
First theselected
selectedtext
textisisstored
storedininaavariable.
variable.Next,
Next,define
defineaareference
referencetotothe
theclipboard,
clipboard,and
and
thetext
the textisisstored
storedininan
anobject
objectofofthe
thetype
typeStringSelection,
StringSelection,and
andthis
thisobject
objectisissaved
savedom
omthethe
clipboard.
clipboard.The Thenext
nexthandler
handlerinserts
insertstext
textstored
storedononthe
theclipboard
clipboardininthe
thedocument:
document:

private void paste(ActionEvent e)


{
try
{
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable data = cb.getContents(this);
if (data == null) return;
String str = (String)data.getTransferData(DataFlavor.stringFlavor);
String text = txtDoc.getText();
int p = txtDoc.getSelectionStart();
int q = txtDoc.getSelectionEnd();
if (q > p) txtDoc.setText(q < text.length() ?
text.substring(0, p) + str + text.substring(q + 1) :
text.substring(0, p) + str);
else
{
p = txtDoc.getCaretPosition();
txtDoc.setText(text.substring(0, p) + str + text.substring(p));
}

116
116
116
JAVA 2:
JAVA
JAVA 2: PROGRAMS
2: PROGRAMS WITH
PROGRAMS WITH A
WITH A
A
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE
GRAPHICAL USER INTERFACE paedIt
Paedit
paedIt

changed == true;
changed true;
setStatus();
setStatus();
}}
catch (Exception
catch (Exception ex)
ex)
{{
JOptionPane.showMessageDialog(this,
JOptionPane.showMessageDialog(this,
"The text
"The text could
could not
not be
be pasted
pasted from
from the
the clipboard",
clipboard",
"Error message", JOptionPane.OK_OPTION);
"Error message", JOptionPane.OK_OPTION);
}}
}}

The
The handler
handler first
first defines
defines aaa reference
reference toto the
the clipboard,
clipboard, andand the
the value
value isis taken
taken asas an
an object
object of
of
The handler first defines reference to the clipboard, and the value is taken as an object of
the type
the type Transferable.
type Transferable. The
Transferable. The object
The object is
object is converted
is converted into
converted into a String
into aa String with
String with a method
with aa method getTransfereData().
method getTransfereData().
getTransfereData().
the
This string
This string must
string must
must be be inserted
be inserted into
inserted into the
into the input
the input field,
input field, either
field, either
either toto replace
to replace a selected
selected text
replace aa selected text or
or inserted
inserted
This text or inserted
at
at the
the cursor
cursor position.
position. The
The event
event handler
handler cut()
cut() works
works in in principle
in principle
principle inin the
in the same
the same way.
same way.
way.
at the cursor position. The event handler cut() works

Back
Back is
is the
the event
event handler
handler for search:
for search:
search:
Back is the event handler for

private void
private void search(ActionEvent
search(ActionEvent e)
e)
{
{
String str
String str == JOptionPane.showInputDialog(this,
JOptionPane.showInputDialog(this, "Enter
"Enter aa search
search text",
text", "Search",
"Search",
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.INFORMATION_MESSAGE);

117
117
117
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
JAVA 2:
JAVA 2: PROGRAMS
GRAPHICAL PROGRAMS
USER WITH AA
WITH
GRAPHICAL USERINTERFACE
INTERFACE Paedit
paedIt
GRAPHICAL USER INTERFACE
GRAPHICAL USER INTERFACE paedIt
paedIt

if (str != null && str.length() > 0)


if (str
if (str !=
!= null
null &&
&& str.length()
str.length() >> 0)
0)
{
{
{
String text = txtDoc.getText();
String text
String text == txtDoc.getText();
txtDoc.getText();
int p = text.indexOf(str);
int p = text.indexOf(str);
int p = text.indexOf(str);
if (p >= 0)
if (p
if (p >=
>= 0)
0)
{
{
{
txtDoc.select(p, p + str.length());
txtDoc.select(p, pp ++ str.length());
txtDoc.select(p, str.length());
txtDoc.requestFocus();
txtDoc.requestFocus();
txtDoc.requestFocus();
}
}
}
else JOptionPane.showMessageDialog(this, "The text does not exist",
else JOptionPane.showMessageDialog(this,
else JOptionPane.showMessageDialog(this, "The
"The text
text does
does not
not exist",
exist",
"Information", JOptionPane.OK_OPTION);
"Information", JOptionPane.OK_OPTION);
"Information", JOptionPane.OK_OPTION);
}
}
}
}
}
}

ItItIt does
Itdoes
doesnot
does
not
notwork
not
work
work
quite
workquite
quiteas
quite
as
asititit
as
should,
itshould, since
sinceititit
should,since
should, since
only
itonly
onlyfinds
only
finds the
findsthe
finds
first
thefirst
the
occurrence
firstoccurrence
first occurrenceof
occurrence
of the
ofthe
of
search
thesearch
the search
search
string.
string. It is a limitation
string.ItItItisisisaaalimitation
limitationof of a JTextArea.
ofaaaJTextArea.
JTextArea.TheThe
Thecodecode is easy
codeisisiseasy enough
easyenough
enoughto to understand,
tounderstand,
understand,but but you
butyou must
youmust
must
string. limitation of JTextArea. The code easy enough to understand, but you must
thethe enter
enter
the enter
enter search search
search text.
text.
search text. For
For
text. For this
this
For this purpose
purpose
this purpose is
is used
used
purpose isis used
used ananan input
input
an input dialog,
dialog,
input dialog, which
which
dialog, which is
is a a simple
simple
which isis aa simple popup
popup
simple popup
popup
the
where
where
whereyou you
youcan can enter
canenter a string,
enteraaastring,
string,and and the
andthe popup
thepopup is opend
popupisisisopend
opendwith with the
withthe method
themethod showInputDialog()
methodshowInputDialog()
showInputDialog()
where you can enter string, and the popup opend with the method showInputDialog()
that
that is a method
thatisisisaaamethod
methodin in the
inthe class
theclass JOptionPane.
classJOptionPane.
JOptionPane.
that method in the class JOptionPane.

When
When
Whenthe the window
windowisisis
thewindow closed
isclosed (and
closed(and
(andthethe program
theprogram stops),
stops),IIIIwant
programstops), want
wanttoto test
totest whether
testwhether
whetherthe the document
thedocument
document
When the window closed (and the program stops), want to test whether the document
is changed
isisischanged and
changedand possibly
andpossibly should
possiblyshould
shouldbe be saved.
besaved. For
saved.For
Forthisthis purpose,
thispurpose, I has
purpose,IIIhas written
haswritten
writtenanan inner
aninner class
innerclass that
classthat
that
changed and possibly should be saved. For this purpose, has written an inner class that
implements
implements
implementsan an event
anevent handler
eventhandler
handlerforfor the
forthe event,
theevent, that
event,that
thatthethe window
thewindow closes:
windowcloses:
closes:
implements an event handler for the event, that the window closes:
class WindowCloser extends WindowAdapter
class WindowCloser
class WindowCloser extends
extends WindowAdapter
WindowAdapter
{
{{
public void windowClosing(WindowEvent e)
public void
public void windowClosing(WindowEvent
windowClosing(WindowEvent e) e)
{
{{
if (changed && JOptionPane.showConfirmDialog(MainView.this,
if (changed
if (changed &&
&& JOptionPane.showConfirmDialog(MainView.this,
JOptionPane.showConfirmDialog(MainView.this,
"The document is changed. Do you want to save it?",
"The document
"The document is
is changed.
changed. Do
Do you
you want
want to
to save
save it?",
it?",
"Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) save();
"Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) save();
"Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) save();
}
}}
}
}}

There
Thereisisis
isnono mystery
nomystery
mysteryin in the
inthe code,
thecode, but
code,but the
butthe window
thewindow must
windowmust be
mustbe defined
bedefined
definedasas
asaaaalistener
listener for
listenerfor the
forthe event,
theevent,
event,
There
There no mystery in the code, but the window must be defined as listener for the event,
that happens
thathappens
happensin in the
inthe constructor:
theconstructor:
constructor:
that
that happens in the constructor:
addWindowListener(new WindowCloser());
addWindowListener(new WindowCloser());
addWindowListener(new WindowCloser());

118
118
118
118
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Paedit

TEST

When the program is finished, it must be tested. In this case there is not much else to do
than try to use the program. However, it can be hard to ensure that you get tested all the
situations that may occur. Here it may help to make a test plan where you write down what
it is you want to test. It naturally gives no guarantee, but partly just that to write the plan
means that you think through what it is you must test, and secondly it helps you remember
to get all the points with when you performs the test. A test plan could for instance be
something like the following:

1. the program’s visual look and feel


2. enter a document
3. save the document
4. enter more text in the same document
5. save it again
6. close the program
7. open the document again
8. edit the content
9. save the document
10. copy text to the clipboard
11. paste the text in the document without replace
12. paste the text in the document and replace selected text
13. cut a selected text
14. paste the text in the document again
15. copy text from another program to this program
16. test the search functionen
17. save the document
18. create a new document
19. open the test document again
20. modify the document
21. close the program without saving the document
22. open the program again
23. open test document
24. open another text document, as an example a java program
25. open a document, that is not text

Later I will deal with testing programs, but a simple test plan as above is better than nothing.
One should however be aware that if you find errors during the test, the errors must of
course be corrected, and then repeat the test – all the points in the test plan again – and
repeating the process until you have completed a test without errors.

119
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Final example

8 FINAL EXAMPLE
The task is to write a program that simulates a solitaire. It is a very simple solitaire game
where the rules are as follows:

On the table is 16 cards. One must then remove the cards on two criteria:

1. cards of the same color with value less than 10, and where the sum of the card’s
values are 15 (thus as an example es, five and nine in the same color, or seven and
eight in the same color)
2. 10, Jack, Queen and King of the same color

When you have removed cards, the unused places must be filled with cards from the deck –
if there are more cards. The solitaire is solved when all cards are removed, but when you
get into a situation where you can not remove cards, it means that the solitaire can not
be solved.

120
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Final example

8.1 THE PROGRAM’S CLASSES


In principle, it is a very simple program in which the user interface has to display images
of playing cards, which the user then should be able to click on with the mouse. The
program has in principle no other functions, but there must be a possibility to be able to
select new game.

There must be kept track of which cards are on the table, which are left in the deck and
which have been taken, and for this purpose the program should define a model that always
represents the program’s current state. The program must therefore in principle work in that
way, that when the user clicks on a card, a message is sent to the model on which card
is clicked, and the model should then from the cards that are marked determine whether
the cards can is removed from the table according to the solitaires rules. If this is the case
the model must remove the cards from the table, and selecting new cards from the deck.

The basic concept in the program is a playing card, which is a very simple concept. A
playing card must have three characteristics:

1. a value that must be a number from 1 to 13: 1 = es, 11 = Jack, 12 = Queen and
13 = king
2. a color which should be a character: D (diamonds), H (Hearts), S (spade) C (clubs)
3. an image of the card

Otherwise, a card is passive and can be defined as follows:

Besides a playing card it is also natural to think of a deck of 52 cards. It is not much more
than an array of 52 Card objects and a variable that can keep track of how many cards are
left in the deck:

121
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Final example

The first method returns while the deck is empty, and the next how many cards left in the
deck. The third method returns and remove the card that is on top of the deck and as so
simulates that a dealer share a card. The last method shuffles the cards and should be used
when selecting a new game.

The model must have an object of type Cards, and thus a deck of cards. In order to control
the game’s state is needed three data structures

-- a list of the cards that has been taken


-- an array that keeps track of which cards are on the table
-- an array which keeps track of which of the cards on the table is marked

and thus you can outline the model class as follows:

The class has only two essential methods, where move() is the most important and is used
each time the user clicks on a card. The method reset() is for selecting new game.

The program’s design will consist of the following classes:

122
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Final example
GRAPHICAL USER INTERFACE FInal exaMple

8.2 PROGRAMMING
8.2 PROGRAMMING
The starting point is a NetBeans project called Solitaire16. To write the program you must
The starting point is a NetBeans project called Solitaire16. To write the program you must
have pictures of playing cards. The folder for this book has a package with the name cards.
have pictures of playing cards. The folder for this book has a package with the name cards.
tar.gz containing images of the cards. In addition to the 52 cards, there are also two back
tar.gz containing images of the cards. In addition to the 52 cards, there are also two back
side cards and an icon to be used in a simple toolbar. To get the pictures packed in the
side cards and an icon to be used in a simple toolbar. To get the pictures packed in the
application’s jar file, I’ve created a package named solitaire16.images, unpackaged the tar file
application’s jar file, I’ve created a package named solitaire16.images, unpackaged the tar file
and copied all the images to that folder.
and copied all the images to that folder.

THE MODEL LAYER


THE MODEL LAYER
The model layer is composed of the three classes referred to above, and the class Card is
The model layer is composed of the three classes referred to above, and the class Card is
trivial and are not discussed further. The same applies in principle to the class Cards, but
trivial and are not discussed further. The same applies in principle to the class Cards, but
it is this class that has to load the images to the cards, and for this I added a helper class
it is this class that has to load the images to the cards, and for this I added a helper class
with a method that can load an image from the jar file:
with a method that can load an image from the jar file:

package solitaire16;

import java.awt.Color;
import javax.swing.*;

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

123
123
JAVA
JAVA2:2:PROGRAMS
PROGRAMSWITH
WITHAA
JAVA 2: PROGRAMS
GRAPHICAL
GRAPHICAL USER WITH A
USERINTERFACE
INTERFACE Final
FInalexample
exaMple
GRAPHICAL USER INTERFACE FInal exaMple

public class Tools


public class Tools
{
{
public static Color selected = Color.darkGray;
public static Color selected = Color.darkGray;

public static ImageIcon createImage(String path, String description)


public static ImageIcon createImage(String path, String description)
{
{
java.net.URL imgURL = Cards.class.getResource(path);
java.net.URL imgURL = Cards.class.getResource(path);
if (imgURL != null) return new ImageIcon(imgURL, description);
if (imgURL != null) return new ImageIcon(imgURL, description);
return null;
return null;
}
}
}
}

The classreally
The really doesnot
not belongininthe
the modellayer,
layer, sinceitsits purposeisistotocreate
create ImageIcon
Theclass
class reallydoes
does notbelong
belong in themodel
model layer,since
since itspurpose
purpose is to createImageIcon
ImageIcon
objectsthat
objects thatare
areobjects
objectsthat
thatbelongs
belongstotothetheuser
userinterface.
interface.On Onthethewhole,
whole,the theboundary
boundary
objects that are objects that belongs to the user interface. On the whole, the boundary
between modeland
between and viewlayers
layers in thecurrent
current solutionisisnotnot quitesharpsharp becausethe the classes
betweenmodel
model andviewview layersininthe
the currentsolution
solution is notquitequite sharpbecause
because theclasses
classes
inthe
inin themodel
modellayer
layerare
areusing
usingobjects
objectsthat
thatbelongs
belongstotothe
theview
viewlayer,
layer,and
andthe theprogram
programthen
then
the model layer are using objects that belongs to the view layer, and the program then
does notmeets
does meets theprinciple
principle behindMVCMVC as themodel model layerininaamanner
manner knowsthe the view
doesnot
not meetsthethe principlebehind
behind MVCasasthe the modellayer
layer in a mannerknows knows theview
view
layer.One
layer. Onecancanmade
madeaadifferent
differentdesign
designofofthe
theprogram,
program,where
wherethe theclasses
classesininthe
themodel
modellayer
layer
layer. One can made a different design of the program, where the classes in the model layer
does notknow
does know theimages,
images, butyouyou canalso
also takethethe currentsolution
solution of theprogram
program as an
doesnot
not knowthe the images,but
but youcancan alsotake
take thecurrent
current solutionofofthe the programasasan an
exampleofofhow
example howpatterns
patternsand
andprinciples
principlesarearegood,
good,butbutconversely
converselyyou youshould
shouldnot notcomplicate
complicate
example of how patterns and principles are good, but conversely you should not complicate
the codejust
the just to complyaapattern.
pattern.
thecode
code justtotocomply
comply a pattern.

With theabove
With above classavailable,
available, it is simpletotowrite
write thecode
code forthe
the classCards.
Cards. It mustload
load
Withthethe aboveclass
class available,ititisissimple
simple to writethe
the codefor
for theclass
class Cards.ItItmust
must load
the 52playing
the playing cardsinto
into anarray,
array, andininaddition
addition loadthe
the imagestototwotwo backcards.
cards. The
the5252 playingcards
cards intoanan array,and and in additionload
load theimages
images to twobackback cards.The The
classalso
class alsohas
hasaamethod
methodtotoshuffle
shufflethe thecards,
cards,which
whichisisdone
donewith
withthe
thefollowing
followingalgorithm:
algorithm:
class also has a method to shuffle the cards, which is done with the following algorithm:
public void shuffle()
public void shuffle()
{
{
for (int n = 0; n < 1000; ++n)
for (int n = 0; n < 1000; ++n)
{
{
int i = rand.nextInt(array.length);
int i = rand.nextInt(array.length);
int j = rand.nextInt(array.length);
int j = rand.nextInt(array.length);
Card temp = array[i];
Card temp = array[i];
array[i] = array[j];
array[i] = array[j];
array[j] = temp;
array[j] = temp;
}
}
top = array.length;
top = array.length;
}
}

124
124
124
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE Final example
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH AA
GRAPHICAL USER INTERFACE FInal exaMple
GRAPHICAL USER INTERFACE
GRAPHICAL USER INTERFACE FInal
FInal exaMple
exaMple

The class Model defines the following instance variables:


The class Model defines the following instance variables:
The
The class
class Model
Model defines
defines the
the following
following instance
instance variables:
variables:
public class Model
public class Model
{public class Model
{{
private Cards deck = new Cards(); // the deck of cards to be used
private
private Cards
Cards deck
deck == new
new Cards();
Cards(); //
// the
the deck
deck of cards
of are
cards to
to be
be used
used
private ArrayList<Card> used = new ArrayList(); // the cards taken
private
private ArrayList<Card>
ArrayList<Card> used
used == new
new ArrayList();
ArrayList(); //
// the
the cards
cards are
are taken
taken
private Card[][] table = new Card[4][4]; // the cards on the table
private Card[][]
Card[][] table
private boolean[][]table == new
new Card[4][4];
Card[4][4]; // the
the cards
// cards cards on the table
private marked = new boolean[4][4]; // that on
is the table
marked
private
private boolean[][]
boolean[][] marked
marked == new
new boolean[4][4];
boolean[4][4]; //
// cards
cards that
that is
is marked
marked

In
In addition
addition to
to what
what isis shown
shown in in the
the design
design isis the
the class
class extended
extended by by aa number
number of of other
other
In
In addition
addition to
to what
what isis shown
shown in in the
the design
design isis the
the class
class extended
extended by by aa number
number of of other
other
methods,
methods, which
which has
has the
the sole
sole purpose
purpose thatthat the
the user
user interface
interface can can read
read the
the model’s
model’s state.
state. As
As
methods,
methods, which
which has
has the
the sole
sole purpose
purpose thatthat the
the user
user interface
interface can can read
read the
the model’s
model’s state.
state. As
As
mentioned,
mentioned, the
the method
method move()
move() isis the
the most
most complex,
complex, as as itit isis the
the method
method to to test
test whether
whether the
the
mentioned,
mentioned, the
the method
method move()
move() isis the
the most
most complex,
complex, as as itit isis the
the method
method to to test
test whether
whether the
the
cards
cards may
may be
be removed
removed from
from thethe table.
table. This
This isis done
done with
with the the following
following algorithm:
algorithm:
cards
cards may
may bebe removed
removed from
from thethe table.
table. This
This isis done
done with
with the the following
following algorithm:
algorithm:
if all cards has the same color then
if
if all
all cards
cards has the same color then
calculate thehas
sumthe
of same color values
the cards then
calculate
calculate the sum of the cards values
if there isthe sum of
a face cardthethen
cards values
if
if there
there is
is aa face
face card
card then
then
if the sum = 46 then move cards
if
if the
the sum
sum == 4646 then
then move
move cards
cards
else
else
else
if the sum = 15 then move cards
if
if the
the sum
sum == 1515 then
then move
move cards
cards

THE PROGRAM’S
THE PROGRAM’S VIEW
VIEW
THE
THE PROGRAM’S
PROGRAM’S VIEW
VIEW
The user
The user interface
interface contains
contains only
only aa single
single class,
class, which
which isis MainWindow.
MainWindow. The
The class
class does
does not
not
The
The user
user interface
interface contains
contains only
only aa single
single class,
class, which
which isis MainWindow.
MainWindow. The
The class
class does
does not
not
take up
take up so
so much
much and
and defines
defines the
the following
following instance
instance variables:
variables:
take
take up
up so
so much
much and
and defines
defines the
the following
following instance
instance variables:
variables:
public class MainWindow extends JFrame
public class MainWindow extends JFrame
{public class MainWindow extends JFrame
{{
private Model model = new Model();
private Model
Model model
private JLabel[][] == new
modelcenternew =Model();
Model();
private new JLabel[4][4];
private
private JLabel[][]
JLabel[][] center
center =
= new
new JLabel[4][4];
JLabel[4][4];
private JLabel[] left = new JLabel[36];
private
private JLabel[]
JLabel[] left
left == new
new JLabel[36];
JLabel[36];
private JLabel[] right = new JLabel[52];
private
private JLabel[]
JLabel[] right
right == new
new JLabel[52];
JLabel[52];

Here isis the


Here the center
center for
for the
the cards
cards on
on the
the table,
table, left
left isis the
the deck
deck and
and must
must show
show which
which cards
cards
Here
Here isis thethe center
center for
for the
the cards
cards on
on the
the table,
table, left
left isis the
the deck
deck and
and must
must show
show which
which cards
cards
are left
are left in
in the
the deck,
deck, and
and finally
finally right
right for
for the
the cards
cards that
that areare taken.
taken. center
center shows
shows cards
cards spread
spread
are
are left
left in
in the
the deck,
deck, and
and finally
finally right
right for
for the
the cards
cards that
that are
are taken.
taken. center
center shows
shows cards
cards spread
spread
out over
out over thethe table
table with
with the
the front
front up,
up, while
while right
right shows
shows the the cards
cards that
that isis taken
taken as
as aa deck.
deck.
out
out over
over thethe table
table with
with thethe front
front up,
up, while
while right
right shows
shows thethe cards
cards that
that isis taken
taken as
as aa deck.
deck.
left shows
left shows justjust aa backing
backing card:
card:
left shows just a backing
left shows just a backing card: card:

125
125
125
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Final example

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

126
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE Final example

The window layout is a BorderLayout, where NORTH has a toolbar with a single button,
WEST has the deck with the cards not yet dealt, EAST has a deck with the cards taken,
and finally the 16 cards on the table are CENTER.

The images for the cards are displayed with a JLabel that specifically can display an image.
To show that a card is marked when it is clicked, the background color for the JLabel
component that contains the image is changed, and it appears as a frame around the picture.
The color is defined in the class Tools.

It is a very simple solitaire, but it is relatively difficult to solve the solitaire, and you get
very quick in a situation where you have to give up, so there is no question of that it is
not the most entertaining solitaire.

127
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example

9 A LAST EXAMPLE
As shown in this book require the programming of a graphical user interface many lines of
code, and there is even talk of code that is difficult to remember how to write. Conversely,
the book’s examples also shows that it is the same thing you have to write every time, or at
least that the development of the various user interfaces have a number of common features.
One can facilitate the work by creating a class library that contains classes with methods
of the tasks typically encountered, and this library can then be made available to all of the
GUI programs that you develop.

I will in this last chapter show how to write such a class library, which I will call PaLib, and
I also shows a program that use the library. The class library is used in all subsequent books
and not only that, the library will continuously be expanded and more of the upcoming
exercises and problems actually has to do with how to expand the library. You are therefore
encouraged to carefully study how the class library is made and how it is used in the program
History, a test program that I shows last in this chapter. Although the program relative to
GUI programs do not contain anything new, it is nevertheless an appropriate conclusion
to this introduction to GUI applications and Swing.

9.1 CREATING THE LIBRARY


In principle, it is quite simple to create a class library, and in NetBeans you creates a project
in the usual way, just it have to be a Java Class Library project:

128
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example
GRAPHICAL USER INTERFACE a last exaMple

The
The result
result isis aa project
project that
that isis empty,
empty, and
and you
you can
can then
then start
start to
to add
add packages
packages and and classes.
classes.
My library is as mentioned called PaLib, and so far it consists
My library is as mentioned called PaLib, and so far it consists only of a single package only of a single package
named
named palib.gui
palib.gui and and aa single
single class
class called
called Tools
Tools (se(se below).
below). TheThe class
class consists
consists exclusively
exclusively of of
static methods that are methods that I find useful in the design
static methods that are methods that I find useful in the design of user interfaces. I will of user interfaces. I will
not
not show
show the
the codecode here,
here, as
as itit isis extensive
extensive (it
(it takes
takes up
up 800
800 lines),
lines), but
but many
many of of the
the lines
lines are
are
comments, and the methods are almost all used in the previous
comments, and the methods are almost all used in the previous examples. As an example examples. As an example
II will
will show
show aa single
single method
method (in (in several
several overloadings),
overloadings), which which shows
shows aa little
little about
about what
what the
the
class contains.
class contains.

ItIt isis aa method


method that
that creates
creates aa JTextField:
JTextField:

/**
* Creates and returns a JTextField with the following properties:
* @param width The width of the field
* @param height The height of the field

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

129
129
JAVA
JAVA 2:
2: PROGRAMS
PROGRAMS WITH
WITH AA
GRAPHICAL
GRAPHICAL USER
USER INTERFACE
INTERFACE Aa last
last example
exaMple

* @return A JTextField component


*/
public static JTextField createField(int width, int height)
{
return createField(null, JTextField.LEFT, true, width, height, null, null, null);
}

/**
* Creates and returns a JTextField with the following properties:
* @param text The text that must initialize the field
* @param width The width of the field
* @param height The height of the field
* @return A JTextField component
*/
public static JTextField createField(String text, int width, int height)
{
return createField(text, JTextField.LEFT, true, width, height, null, null, null);
}

/**
* Creates and returns a JTextField with the following properties:
* @param text The text that must initialize the field
* @param width The width of the field
* @param height The height of the field
* @param font The font to be used
* @return A JTextField component
*/
public static JTextField createField(String text, int width, int height, Font font)
{
return createField(text, JTextField.LEFT, true, width, height, font, null, null);
}

/**
* Creates and returns a JTextField with the following properties:
* @param text The text that must initialize the field
* @param alignment The text alignment, can be JTextField.LEFT or JTextField.RIGHT
* @param editable Where the contents of the field may be edited or not
* @param width The width of the field
* @param height The height of the field
* @param font The font to be used
* @return A JTextField component
*/
public static JTextField createField(String text,
int alignment, boolean editable,
int width, int height, Font font)
{
return createField(text, alignment, editable, width, height, font, null, null);
}

130
130
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example
GRAPHICAL USER INTERFACE a last exaMple

/**
* Creates and returns a JTextField with the following properties:
* @param text The text that must initialize the field
* @param alignment The text alignment, can be JTextField.LEFT or JTextField.RIGHT
* @param editable Where the contents of the field may be edited or not
* @param width The width of the field
* @param height The height of the field
* @param font The font to be used
* @param fg The field's text color
* @param bg The field's background color
* @return A JTextField component
*/
public static JTextField createField(String text, int alignment, boolean editable,
int width, int height, Font font, Color fg, Color bg)
{
JTextField field = new JTextField();
if (text != null) field.setText(text);
field.setHorizontalAlignment(alignment);
field.setEditable(editable);
if (font != null) field.setFont(font);
if (fg != null) field.setForeground(fg);
if (bg != null) field.setBackground(bg);
field.setPreferredSize(new Dimension(width, height));
return field;
}

AsAsregards
regardsthe
themethods
methodsthemselves,
themselves,andandhow
howthey
theywork,
work,there
thereisisnot
notmuch
muchtotoexplain,
explain,but
but
I Iwill tell you about the considurations concerning the method createField().
will tell you about the considurations concerning the method createField(). In practice, In practice,
I Ioften
oftenneed
needtotocreate
createaaJTextField
JTextFieldandandI Ioften
oftenhas
hastotoinitialize
initializeseveral
severalproperties.
properties.ItItmay
may
therefore
thereforebebeuseful
usefulwith
withaamethod
methodwhich
whichparameters
parametershas hasvalues
valuesforforthe
theproperties
propertiestotobebeset,
set,
and
andaamethod
methodthatthatcreates
createsandandreturns
returnsaaJTextField
JTextFieldwith
withthese
theseproperties
propertiesinitialized.
initialized.Now
Now
you can define many properties of a JTextField, and it would not be appropriate
you can define many properties of a JTextField, and it would not be appropriate by methods by methods
ofofall
allpossible
possiblecombination
combinationofofproperties,
properties,but
butthe
thelast
lastversion
versionofofthethemethod
methodcreateField()
createField()
has
hasparameters
parametersfor forthe
themost
mostcommon
commonproperties
properties––atatleast
leastininrelation
relationtotothe
theprograms
programsthatthat
I Iwrite.
write.Since
Sincethere
thereisisfar
farfrom
fromalways
alwaysneed
needofofall
allthese
theseparameters,
parameters,I Ihave
havewritten
writtenseveral
several
overloading methods that has fewer parameters.
overloading methods that has fewer parameters.

When
Whenyou youhave
havetotowrite
writethat
thatkind
kindofoflibrary
libraryclasses
classesthe
thebiggest
biggestconsiderations
considerationsarearewhat
what
parameters
parametersthethemethods
methodsshould
shouldhave.
have.OnOnthe theone
onehand,
hand,methods
methodsshould
shouldhave
havesosomany
many
parameters
parameters that they are flexible enough to be used as tools in many applications. Onthe
that they are flexible enough to be used as tools in many applications. On the
other hand there should not be so many parameters that it is confusing
other hand there should not be so many parameters that it is confusing and the methodsand the methods
equally
equallybecomes
becomesdifficult
difficulttotouse.
use.TheThechoice
choiceshould
shouldreflect
reflecttypical
typicalapplications,
applications,and
andininthis
this
case
casethe
theneeds
needsI Itypically
typicallyhave
havetotocreate
createaaJTextField.
JTextField.

131
131
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example

I shall not show the rest of the class, but there are similar methods to create the most basic
Swing components. Furthermore, there are methods to place components in the containers.
This is a class with tools, and it is natural that the class is continuously expanded with new
methods as you need them. Similarly, the class library may be extended with new classes,
and as an example I will extend the library with a class that has methods to write an object
to and read an object from a file.

First I has extended the library with a new package called palib.util and here a class called Files:

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

132
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example
GRAPHICAL USER INTERFACE a last exaMple

InInthe
thebook
bookJavaJava11I Ishows
showshowhowtotostore
storean
anabritary
abritaryobject
objectininaafile
file(object
(objectserialization)
serialization)
and
and how to read the object again (object deserialization). It can be difficult toremember
how to read the object again (object deserialization). It can be difficult to remember
how
how write the statements, and when it is the same you has to write every time itpays
write the statements, and when it is the same you has to write every time it paystoto
write
writetwo
twolibrary
librarymethods
methodsfor forthese
thesepurposes:
purposes:

package palib.util;

import java.io.*;

public class Files


{
public static boolean serialize(Object obj, String filename)
{
try
{
ObjectOutputStream stream =
new ObjectOutputStream(new FileOutputStream(filename));
stream.writeObject(obj);
stream.close();
return true;
}
catch (Exception ex)
{
return false;
}
}

public static Object deserialize(String filename)


{
try
{
ObjectInputStream stream =
new ObjectInputStream(new FileInputStream(filename));
Object obj = stream.readObject();
stream.close();
return obj;
}
catch (Exception ex)
{
return null;
}
}
}

133
133
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS
GRAPHICAL WITH A
USER INTERFACE A last example
GRAPHICAL USER INTERFACE a last exaMple

9.2 THE TEST PROGRAM


9.2 THE TEST PROGRAM
I will finally show how my class library can be used in a program. I have written a program
I will finally show how my class library can be used in a program. I have written a program
called History, where you can maintain a list of historical persons. It requires that the
called History, where you can maintain a list of historical persons. It requires that the
program can save the list somewhere. When the program starts the first time, it initialize
program can save the list somewhere. When the program starts the first time, it initialize
the list of the Danish kings, and each time the list is changed, it is stored in a file on your
the list of the Danish kings, and each time the list is changed, it is stored in a file on your
hard disk. When the program opens the next time, it starts to read the updated list from
hard disk. When the program opens the next time, it starts to read the updated list from
the file – if possible. Otherwise the list is initialized of the Danish kings. The file is stored
the file – if possible. Otherwise the list is initialized of the Danish kings. The file is stored
in the same location as the program and you do not need to study how the file is stored
in the same location as the program and you do not need to study how the file is stored
and read, as the library has the necessary methods.
and read, as the library has the necessary methods.

A person is defined as follows (where I removed the comments and all the get and set methods):
A person is defined as follows (where I removed the comments and all the get and set methods):

package history;

import java.io.*;

public class Person implements Comparable<Person>, Serializable


{
private String name; // the person's name
private String job; // the person's position
private String text; // a description
private int from; // birth, start of reign or otherwise
private int to; // year of when the person is dead

public Person(String name, String job, String text, int from, int to)
{
this.name = name;
this.job = job;
this.text = text;
this.from = from;
this.to = to;
}

….

When
Whenyou youread
readthe
thecode,
code,you
youshould
shouldspecifically
specificallynoting
notinghow
howthethecomparison
comparisonofofobjects
objectsare
are
defined
definedbybythe
themethod
methodcompareTo()
compareTo()where
wherethe
theobjects
objectscompared
comparedby bythe
theyear
yearnumbers
numbers(the
(the
class implements the interface Comparable<Person>), and note that the class
class implements the interface Comparable<Person>), and note that the class implements implements
the
theinterface
interfaceSerializable.
Serializable.You
Youshould
shouldalso
alsonote
notethat
thatthe
theclass
classoverrides
overridesequals(),
equals(),sosopeople
people
are
arecompared
comparedsolely
solelyonontheir
theirnames.
names.

134
134
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example
GRAPHICAL USER INTERFACE a last exaMple

Then
Thenthere
thereisisthe
theclass
classPersons
Personsrepresenting
representingthe
thelist
listofofPerson
Personobjects.
objects.

package history;

import java.util.*;
import palib.util.*;

public class Persons implements Iterable<Person>


{
private static String filename = "persons.dat";
private ArrayList<Person> list;

public Persons()
{
list = (ArrayList<Person>)Files.deserialize(filename);

360°
if (list == null) initialize();
}

.
public Iterator<Person> iterator()

thinking
{
return list.iterator();
}

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


135
135
JAVA 2: PROGRAMS WITH A
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example
GRAPHICAL USER INTERFACE a last exaMple

public void add(Person pers)


{
list.add(pers);
Collections.sort(list);
Files.serialize(list, filename);
}

public void remove(Person pers)


{
list.remove(pers);
Files.serialize(list, filename);
}

public void update(Person pers)


{
for (Person p : list)
{
if (p.equals(pers))
{
p.setJob(pers.getJob());
p.setText(pers.getText());
p.setFrom(pers.getFrom());
p.setTo(pers.getTo());
break;
}
}
Files.serialize(list, filename);
}

private void initialize()


{
list = new ArrayList();
for (int i = 0;i < navne.length; ++i)
{
String job = navne[i][0].equals("Margrete d. 1.") ||
navne[i][0].equals("Margrethe d. 2.") ? "Queen" : "King";
int fra = navne[i][1].length() > 0 ? Integer.parseInt(navne[i][1]) : -9999;
int til = navne[i][2].length() > 0 ? Integer.parseInt(navne[i][2]) : 9999;
list.add(new Person(navne[i][0], job, "", fra, til));
}
Collections.sort(list);
}

private static String[][] navne = {


{ "Gorm den Gamle", "", "958" },
{ "Harald Blåtand", "958", "986" },

};
}

136
136
JAVA2:2:PROGRAMS
JAVA PROGRAMSWITH
WITHAA
GRAPHICALUSER
GRAPHICAL USERINTERFACE
INTERFACE Aalast
lastexample
exaMple

Firstyou
First younote
notethe
theimport
importstatement
statement

import palib.util.*;

referringtotothe
referring thepackage
packagecontaining
containingthetheclass
classFiles.
Files.InInorder
ordertotobebepossible,
possible,the
thejar
jarfile
filefor
forthe
the
classlibrary
class librarymust
mustbebeavailable
availablefor
forthe
theprogram.
program.ItItisisobtained
obtainedfor forthe
theproject
project(the
(theprogram
program
History),by
History), byright-click
right-clickon onLibraries
Librariesand
andhere
herechoose
chooseAdd AddJAR
JAR/ /Folder…You
Folder…Youcan canthen
thenbrowse
browse
totoclass
classlibrary’s
library’sjar
jarfile
fileand
andadd
additittotothe
theproject:
project:

Nowthe
Now theapplication
applicationcan canuse
usethe
thejar
jarfile
fileand
anditsitsclasses.
classes.IfIfwe
wenow
nowbuilds
buildsthetheproject
projectand
and
copythe
copy thefile
fileHistory.jar
History.jartotoanother
anotherfolder
folderandandtry trytotorun
runthe theprogram
programfrom froma aTerminal
Terminal
window,you
window, yougetgetananerror
errormessage
messagebecause
becausethe theprogram
programcan cannotnotfind
findthetheclass
classlibrary.
library.The
The
classlibrary
class libraryisisnot
notpart
partofofthe
theprogram’s
program’sjar-file.
jar-file.IfIfyou
youopens
opensthe theproject’s
project’sdistdistfolder,
folder,you
you
willsee
will seethat
thatthere
thereisisa asubdirectory
subdirectorynamed
namedlib. lib.ItItcontains
containsthe thejar
jarfile
filetotoclass
classlibrary,
library,and
and
forthe
for theprogram
programtotorun,run,this
thissubfolder
subfoldermustmustalsoalsobebecopied.
copied.

Theclass
The classPersons
Personsisisininprinciple
principlesimple
simpleandandyou
youshould
shouldnotice
noticehowhowPerson
Personobjects
objectsare
arestored
stored
ininananArrayList,
ArrayList,andandthetheclass
classhas
hasmethods
methodstotoaddaddananitem,
item,update
updateananitem,
item,and
anddelete
deleteanan
item.Note
item. Notespecifically
specificallythat
thateach
eachofofthese
thesemethods
methodsserialize
serializethe
thelist
listusing
usingthe
themethod
methodserialize()
serialize()
ininthe
theclass
classFiles,
Files,which
whichare area aclass
classininthe
theclass
classlibrary.
library.

Themost
The mostcomplex
complexininthe
theclass
classisisthe
theconstructor.
constructor.ItIttries
triestotodeserialize
deserializethe
thelist
listfrom
froma afile.
file.IfIf
thisfails,
this fails,for
forexample
examplebecause
becausethe thefile
filedoes
doesnot
notexist
exist(and
(andindeed
indeedititdoes
doesnot
notthe thefirst
firsttime
time
theprogram
the programruns),
runs),the
thelist
listisisinitialized
initializedusing
usingdata
datathat
thatisislaid
laidout
outininthe
theprogram
program(Danish(Danish
kingsand
kings andI Ihave
haveonly
onlyshown
shownthe thefirst
firsttwo).
two).The
Thelist
listisiscreated
createdininthe
themethod
methodinitialize(),
initialize(),
whichruns
which runsthrough
throughthe
thestatic
staticarray
arraywithwithdata.
data.

Youshould
You shouldalso
alsonote
notethe
themethod
methoditerator().
iterator().ItItwill
willfirst
firstbebeexplained
explainedininthe
thenext
nextbook,
book,but
but
ititmeans
meansthat
thatititisispossible
possibletotoiterate
iterateover
overa aPersons
Personsobject’s
object’sitems
itemswith
witha afor
forstatement.
statement.

137
137
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example

If you run the program, you get a window as shown below. The window is the program’s
main window, and I will not show the code here, as there not is something new, but you
should notice how the class use the class library for constructing the user interface.

If you double click on a line (a name) in the list, you get a window where you can see
all the information, edit them and possibly delete the person (see below). The class is
named PersonView, where I will not show the code, but the window layout is defined by
a GridBagLayout and the class makes widely use of the class library. If you in the main
window, click the button Create person opens the same window, but with all fields blank,
and you can then enter the name of a person and thus add a new Person to the list.

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

138
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example

Below is an example of the window PersonView, when double clicked on a line in the list box:

139
JAVA 2: PROGRAMS WITH A
GRAPHICAL USER INTERFACE A last example

If you now have many programs that use the class library, each program must have a copy
of the class library’s jar file. Of course it is not particularly useful, and it should be such
that there is only one copy, that all programs are using. It can be solved in several ways,
but a very simple way (although far from the best) is to place the jar file as shown below:

Here are jdk1.8.0_111 the folder containing my Java and can of course be replaced by
another. To make a jar file available in that way by placing it in the folder as shown above
is not necessarily the best way, but it’s a simple way, which is well worth knowing.

140

Вам также может понравиться