Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 9

An Introduction to Java GUI Programming

Introduction
This article is meant for the individual who has little or no experience in Java GUI
programming. As such, this paper will focus on the hierarchal tree structure that roots at the
frame and goes into the content pane panel. The primary focus will then be on the button
widget control in .!"T# and the corresponding method used to handle that event listener.
Any .!"T programmer will find these concepts extremely similar, except that the coding
style re$uires more text is some cases and the terms used are different. A $uic% and easy way
to compile this code on the command line after installing &un's Java (untime at
www.)ava.com and &un's J*"" &+, -.. is to go to the default directory/
c:\Sun\SDK\JDK\bin> type con > somecode.java 0trl12 and then compile. To set your
path/set PATH=%PATH%;.;C:\Sun\SDK\JDK\bin.
Java GUI programming involves two pac%ages/ the original abstract windows %it A3T# and
the newer &wing tool%it. &wing components have the prefix J to distinguish them from the
original A3T ones e.g. JFrame instead of Frame#. To include &wing components and
methods in your pro)ect, you must import the java.aw.!, java.aw.even.!, and java".swin#.!
pac%ages. +isplayable frames are top1level containers such as JFrame, JWindows, JDialog,
and JApplet, which interface with the operating system's window manager. !on1displaying
content panes are intermediate containers such as JPanel, JOptionsPane, JScrollPane, and
JSplitPane. 0ontainers are therefore widgets or GUI controls that are used to hold and
group other widgets such as text boxes, chec% boxes, radio buttons, et al. In .!"T the main
UI, called the 3indows 4orm, holds the controls that are dragged and dropped onto the
control surface. "very GUI starts with a window meant to display things. In &wing, there are
three types of windows/ the Applet, the +ialog, and the 4rame. These interface with the
windows manager. In swing, a frame ob)ect is called a JFrame. A JFrame is considered the
top most container. These are also called displayable frames. !on1displaying content panes
are intermediate containers such as JPanel, JScrollPane, JLayeredPane, JSplitPane and
JTabbedPane which organi5e the layout structure when multiple controls are being used.
&tated simply, the content pane is where we place out text fields are other widgets, so to add
and display GUI controls, we need to specify that it is the content pane that we are adding to.
The content pane is then at the top of a containment hierarchy, in which this tree1li%e
hierarchy has a top1level container in our case JFrame#. 3or%ing down the tree, we would
find other top level containers li%e JPanel to hold the components. 6ere is the code that
produces a simple frame upon to build on/
import javaawt!"
import javaawtevent!"
import java#swing!" $$notice java#
p%blic class Frame& e#tends JFrame
'
JPanel pane ( new JPanel)*"
Frame&)* $$ t+e frame constr%ctor met+od
'
s%per),-y Simple Frame,*" set.o%nds)&//0&//01//0&//*"
setDefa%lt2loseOperation)JFrame345T6O762LOS3*"
2ontainer con ( t+isget2ontentPane)*" $$ in+erit main frame
conadd)pane*" $$ add t+e panel to frame
$$ c%stomi8e panel +ere
$$ paneadd)someWidget*"
set9isible)tr%e*" $$ display t+is frame
:
p%blic static void main)String args;<* 'new Frame&)*":
:
If you have never compiled Java code, then consider this basic code in order to show the
compilation and interpretation process. As .!"T compilers emit I7 code and metadata, where
the metadata tables are read by the 07( to verify type safety that is, that the correct data
types are passed to the correct methods#, the JIT compiler converts the I7 code into native
code for execution. There is no interpretation as there is with the Java 8irtual 9achine. The
Java platform is defined by the A:Is collections of compiled libraries for use programs and
the J89 which is similar to the 07(#. A Java source code file is compiled into byte code
wherein a class file is generated that functions as a blueprint for the runtime execution. 6ere
is an example/
import java%til!"
p%blic class Sys '
p%blic static void main)String;< args* '
Systemo%tprintln
)=T+is is a string passed to t+e print line met+od of t+e System
class>*"
:
:
c?@S%n@SDA@jdB@binCjavace#e Sysjava $$ t+e javace#e compiler
$$ compiles t+e so%rce code
c?@S%n@SDA@jdB@binCjavae#e Sys $$ t+e javae#e interprets t+e byte
code file
$$ )in t+e same directory w+ere t+e class
file is
This is a string passed to the print line method of the System class.
6ere is code that show a GUI with a button.
The button, however, does nothing when pressed/
import javaawt!"
import javaawtevent!"
import java#swing!"
p%blic class FrameD e#tends JFrame
'
JPanel pane ( new JPanel)*"
J.%tton pressme ( new J.%tton),Press -e,*"
FrameD)* $$ t+e frame constr%ctor
'
s%per),JPrompt Demo,*" set.o%nds)&//0&//01//0D//*"
setDefa%lt2loseOperation)JFrame345T6O762LOS3*"
2ontainer con ( t+isget2ontentPane)*" $$ in+erit main frame
conadd)pane*" $$ JPanel containers defa%lt to FlowLayo%t
pressmeset-nemonic)EPE*" $$ associate +otBey to b%tton
paneadd)pressme*" pressmereF%estFoc%s)*"
set9isible)tr%e*" $$ maBe frame visible
:
p%blic static void main)String args;<* 'new FrameD)*":
:
2?@@binCJavace#e FrameDjava

2?@@binCJavae#e FrameD
Java GUIs are event based as they respond to the standard input devices li%e %ey presses,
mouse1clic%s, radio buttons, etc. 6ere is the output of the button press/
import javaawt!"
import javaawtevent!"
import java#swing!"
p%blic class Frame1 e#tends JFrame implements ActionListener
'
JLabel answer ( new JLabel),,*"
JPanel pane ( new JPanel)*" $$ create pane object
J.%tton pressme ( new J.%tton),Press -e,*"
Frame1)* $$ t+e constr%ctor
'
s%per),3vent Gandler Demo,*" set.o%nds)&//0&//01//0D//*"
setDefa%lt2loseOperation)JFrame345T6O762LOS3*"
2ontainer con ( t+isget2ontentPane)*" $$ in+erit main frame
conadd)pane*" pressmeset-nemonic)EPE*" $$ associate +otBey
pressmeaddActionListener)t+is*" $$ register b%tton listener
paneadd)answer*" paneadd)pressme*" pressmereF%estFoc%s)*"
set9isible)tr%e*" $$ maBe frame visible
:
$$ +ere is t+e basic event +andler
p%blic void actionPerformed)Action3vent event*
'
Object so%rce ( eventgetSo%rce)*"
if )so%rce (( pressme*
'
answersetTe#t),.%tton pressedH,*"
JOptionPanes+ow-essageDialog)n%ll0,5 +ear yo%H,0,-essage Dialog,0
JOptionPanePLA576-3SSAI3*" set9isible)tr%e*" $$ s+ow somet+ing
:
:
p%blic static void main)String args;<* 'new Frame1)*":
:
The first step in adding a basic button push event handler to the above example is to import
aw.even.! which contains all of the event classes. !ext add the phrase implements
ActionListener to the class header to use the interface. (egister event listeners for each
button widget using the addActionListener)t+is* method. The reserved word t+is
indicates that the re$uired by implements ActionListener# handler method called
actionPerformed)* will be included in the current class. 4or example, consider this more
colorful example/
import java#swing!"
import javaawt2olor"
p%blic class .%ttonDemo'
p%blic JPanel create2ontentPane )*'
$$ We create a bottom JPanel to place everyt+ing on
JPanel totalIJ5 ( new JPanel)*"
totalIJ5setLayo%t)n%ll*"
$$ 2reation of a Panel to contain t+e title labels
JPanel titlePanel ( new JPanel)*"
titlePanelsetLayo%t)n%ll*"
titlePanelsetLocation)&/0 /*"
titlePanelsetSi8e)DK/0 1/*"
totalIJ5add)titlePanel*"
JLabel redLabel ( new JLabel),Led Team,*"
redLabelsetLocation)/0 /*"
redLabelsetSi8e)&//0 1/*"
redLabelsetGori8ontalAlignment)/*"
redLabelsetForegro%nd)2olorred*"
titlePaneladd)redLabel*"
JLabel bl%eLabel ( new JLabel),.l%e Team,*"
bl%eLabelsetLocation)&D/0 /*"
bl%eLabelsetSi8e)&//0 1/*"
bl%eLabelsetGori8ontalAlignment)/*"
bl%eLabelsetForegro%nd)2olorbl%e*"
titlePaneladd)bl%eLabel*"
$$ 2reation of a Panel to contain t+e score labels
JPanel scorePanel ( new JPanel)*"
scorePanelsetLayo%t)n%ll*"
scorePanelsetLocation)&/0 M/*"
scorePanelsetSi8e)DK/0 1/*"
totalIJ5add)scorePanel*"
JLabel redScore ( new JLabel),/,*"
redScoresetLocation)/0 /*"
redScoresetSi8e)&//0 1/*"
redScoresetGori8ontalAlignment)/*"
scorePaneladd)redScore*"
JLabel bl%eScore ( new JLabel),/,*"
bl%eScoresetLocation)&D/0 /*"
bl%eScoresetSi8e)&//0 1/*"
bl%eScoresetGori8ontalAlignment)/*"
scorePaneladd)bl%eScore*"
$$ 2reation of a label to contain all t+e J.%ttons
JPanel b%ttonPanel ( new JPanel)*"
b%ttonPanelsetLayo%t)n%ll*"
b%ttonPanelsetLocation)&/0 N/*"
b%ttonPanelsetSi8e)DK/0 O/*"
totalIJ5add)b%ttonPanel*"
$$ We create a b%tton and manip%late it %sing t+e synta# we +ave
$$ %sed before
J.%tton red.%tton ( new J.%tton),Led ScoreH,*"
red.%ttonsetLocation)/0 /*"
red.%ttonsetSi8e)&//0 1/*"
b%ttonPaneladd)red.%tton*"
J.%tton bl%e.%tton ( new J.%tton),.l%e ScoreH,*"
bl%e.%ttonsetLocation)&D/0 /*"
bl%e.%ttonsetSi8e)&//0 1/*"
b%ttonPaneladd)bl%e.%tton*"
J.%tton reset.%tton ( new J.%tton),Leset Score,*"
reset.%ttonsetLocation)/0 M/*"
reset.%ttonsetSi8e)DD/0 1/*"
b%ttonPaneladd)reset.%tton*"

totalIJ5setOpaF%e)tr%e*"
ret%rn totalIJ5"
:
private static void createAndS+owIJ5)* '
JFramesetDefa%ltLooBAndFeelDecorated)tr%e*"
JFrame frame ( new JFrame),;(< J.%tton ScoresH ;(<,*"
$$2reate and set %p t+e content pane
.%tton3#ample demo ( new .%tton3#ample)*"
frameset2ontentPane)democreate2ontentPane)**"
framesetDefa%lt2loseOperation)JFrame345T6O762LOS3*"
framesetSi8e)DK/0 &P/*"
frameset9isible)tr%e*"
:
p%blic static void main)String;< args* '
$$Sc+ed%le a job for t+e eventQdispatc+ing t+read?
$$creating and s+owing t+is applicationEs IJ5
SwingJtilitiesinvoBeLater)new L%nnable)* '
p%blic void r%n)* '
createAndS+owIJ5)*"
:
:*"
:
:
OUTPUT
!othing will happen when the buttons are pressed as the event listener is needed/
import java#swing!"
import javaawt2olor"
import javaawteventActionListener"
import javaawteventAction3vent"
p%blic class .%ttonDemo63#tended implements ActionListener'
$$ Definition of global val%es and items t+at are part of t+e IJ5
int redScoreAmo%nt ( /"
int bl%eScoreAmo%nt ( /"
JPanel titlePanel0 scorePanel0 b%ttonPanel"
JLabel redLabel0 bl%eLabel0 redScore0 bl%eScore"
J.%tton red.%tton0 bl%e.%tton0 reset.%tton"
p%blic JPanel create2ontentPane )*'
$$ We create a bottom JPanel to place everyt+ing on
JPanel totalIJ5 ( new JPanel)*"
totalIJ5setLayo%t)n%ll*"
$$ 2reation of a Panel to contain t+e title labels
titlePanel ( new JPanel)*"
titlePanelsetLayo%t)n%ll*"
titlePanelsetLocation)&/0 /*"
titlePanelsetSi8e)DK/0 1/*"
totalIJ5add)titlePanel*"
redLabel ( new JLabel),Led Team,*"
redLabelsetLocation)/0 /*"
redLabelsetSi8e)&D/0 1/*"
redLabelsetGori8ontalAlignment)/*"
redLabelsetForegro%nd)2olorred*"
titlePaneladd)redLabel*"
bl%eLabel ( new JLabel),.l%e Team,*"
bl%eLabelsetLocation)&1/0 /*"
bl%eLabelsetSi8e)&D/0 1/*"
bl%eLabelsetGori8ontalAlignment)/*"
bl%eLabelsetForegro%nd)2olorbl%e*"
titlePaneladd)bl%eLabel*"
$$ 2reation of a Panel to contain t+e score labels
scorePanel ( new JPanel)*"
scorePanelsetLayo%t)n%ll*"
scorePanelsetLocation)&/0 M/*"
scorePanelsetSi8e)DR/0 1/*"
totalIJ5add)scorePanel*"
redScore ( new JLabel),,SredScoreAmo%nt*"
redScoresetLocation)/0 /*"
redScoresetSi8e)&D/0 1/*"
redScoresetGori8ontalAlignment)/*"
scorePaneladd)redScore*"
bl%eScore ( new JLabel),,Sbl%eScoreAmo%nt*"
bl%eScoresetLocation)&1/0 /*"
bl%eScoresetSi8e)&D/0 1/*"
bl%eScoresetGori8ontalAlignment)/*"
scorePaneladd)bl%eScore*"
$$ 2reation of a Panel to contain all t+e J.%ttons
b%ttonPanel ( new JPanel)*"
b%ttonPanelsetLayo%t)n%ll*"
b%ttonPanelsetLocation)&/0 N/*"
b%ttonPanelsetSi8e)DR/0 O/*"
totalIJ5add)b%ttonPanel*"
$$ We create a b%tton and manip%late it %sing t+e synta# we +ave
$$ %sed before 7ow eac+ b%tton +as an ActionListener w+ic+ posts
$$ its action o%t w+en t+e b%tton is pressed
red.%tton ( new J.%tton),Led ScoreH,*"
red.%ttonsetLocation)/0 /*"
red.%ttonsetSi8e)&D/0 1/*"
red.%ttonaddActionListener)t+is*"
b%ttonPaneladd)red.%tton*"
bl%e.%tton ( new J.%tton),.l%e ScoreH,*"
bl%e.%ttonsetLocation)&1/0 /*"
bl%e.%ttonsetSi8e)&D/0 1/*"
bl%e.%ttonaddActionListener)t+is*"
b%ttonPaneladd)bl%e.%tton*"
reset.%tton ( new J.%tton),Leset Score,*"
reset.%ttonsetLocation)/0 M/*"
reset.%ttonsetSi8e)DK/0 1/*"
reset.%ttonaddActionListener)t+is*"
b%ttonPaneladd)reset.%tton*"

totalIJ5setOpaF%e)tr%e*"
ret%rn totalIJ5"
:
$$ T+is is t+e new ActionPerformed -et+od
$$ 5t catc+es any events wit+ an ActionListener attac+ed
$$ Jsing an if statement0 we can determine w+ic+ b%tton was pressed
$$ and c+ange t+e appropriate val%es in o%r IJ5
p%blic void actionPerformed)Action3vent e* '
if)egetSo%rce)* (( red.%tton*
'
redScoreAmo%nt ( redScoreAmo%nt S &"
redScoresetTe#t),,SredScoreAmo%nt*"
:
else if)egetSo%rce)* (( bl%e.%tton*
'
bl%eScoreAmo%nt ( bl%eScoreAmo%nt S &"
bl%eScoresetTe#t),,Sbl%eScoreAmo%nt*"
:
else if)egetSo%rce)* (( reset.%tton*
'
redScoreAmo%nt ( /"
bl%eScoreAmo%nt ( /"
redScoresetTe#t),,SredScoreAmo%nt*"
bl%eScoresetTe#t),,Sbl%eScoreAmo%nt*"
:
:
private static void createAndS+owIJ5)* '
JFramesetDefa%ltLooBAndFeelDecorated)tr%e*"
JFrame frame ( new JFrame),;(< J.%tton ScoresH ;(<,*"
$$2reate and set %p t+e content pane
.%ttonDemo63#tended demo ( new .%ttonDemo63#tended)*"
frameset2ontentPane)democreate2ontentPane)**"
framesetDefa%lt2loseOperation)JFrame345T6O762LOS3*"
framesetSi8e)DN/0 &P/*"
frameset9isible)tr%e*"
:
p%blic static void main)String;< args* '
$$Sc+ed%le a job for t+e eventQdispatc+ing t+read?
$$creating and s+owing t+is applicationEs IJ5
SwingJtilitiesinvoBeLater)new L%nnable)* '
p%blic void r%n)* '
createAndS+owIJ5)*"
:
:*"
:
:

You might also like