‘0si012023, 13:17 {GUI Programming Part2- Java Programming Tutor
vet another insignificant programming notes... | HOME
TABLE OF CONTENTS (HIDE)
1. More on Swing's 3Components
1. Inagetcon
Java Programming Tutorial 12 Sting the Apparat and
1.3 Display Area, Border and Inset
Programming Graphical User 14 Positioning Your Application V
Interface (GUI) - Part 2 17 wanes ere
2 rast ook an
JDK demo includes a folder "jf", which has many interesting demo on Swing and Java2D.
1. More on Swing's JComponents 3:1 Key Points on Layout Manager
eel oe 52 Meth validate anc dot
The dats hierarchy of Swing’ top-level containers (IFrane, JDialog, Applet) are as 33 odd), renove(), removed
follows. These top-level Swing containers are heavyweight, that rely on the undetying 34 Component Orientation
windowing subsystem of the native platform. 35 Absolute Postoning Without
4, More on Event-Handling
47 java.util Eventobject
42 Action vent & ActionListe
43 Swing’s Action
4d Windowevent & Window. iste
45 KeyEvent & KeyListener/Ke
46 MouseEvent & MouseListenc
47 Mousetvent & MouseMotiont
IFrame | Dialog | dappiet_|
‘The class hierarchy of Swing’s 3Conponents is as fellows. Component and its descendants are lightweight components
|nps:iwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m! ma.‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
object
ae
Component
1
Container <— Layouttanager
— sein
“HForaattedTextFielé|
TTextConponent | aTextares |
TTextes —_
IhackBox
IRadioButten|
2Menuttem
|| Dv stan
burtons one with text el one wih an mage icon, and one with both
text sndicon
The javax. swing. Inagercon class models an image icon. An Inagetcon is a fxed-size picture, typically small, and mainly used for
decorating GUI components. The Inageicon class implements javax.swing..con interface, and hence, often upcasted and
referenced as Icon.
To construct an teageTcon, provide the image filename or URL Image filetype of GIF, PNG, JPG and BMP are supported. For example,
11 Construct an Inagetcon from an image filename
String smgFilenane = "inages/duke.pne*s
1/ Can use an absolute filename such as “c:/project/inages/nought.gif*
Imagetcon iconbuke = new Tnagercon(ingFilenane);
1 08
11 Construct an Inagetcon via an inage URL (in the form of File://path/#ilenane)
Imagelcon iconbuke = null;
‘String ingFilenane = "inages/cuke.png"s
Java.net URL ingURL ~ getClass().getClassLoader()..getResource(IngFilenane);
// Filenare always relative to the root of the project (i.e., bin)
11 can access resource in a JAR file
Sf (JngUaL I= null) ¢
iconduke = mew TnageTcon(imgURL);
p else ¢
Systen.ere.printin(*Couldn't find file: * + dngrilenane);
>
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m! 2182‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
Using URL is more flexible as it can access resources in JAR fle, and produces an error message ifthe file does not exist (which results
jn nul URL.
Many 3Conponents (such a5 3Label, JButton) accepts an Tragetcon in its constructor, or via the setcon() method. For example,
magetcon iconbuke = null;
‘String ingFilenane = "inages/duke.gif"; // relative to project root (or bin)
URL ingual = getClass().getClassLoader() .getResource(ingF lenane) 5
Sf (ngUL 1= null) ¢
iconuke = new Inagercon(inglAL);
p else ¢
Systen.ere.printin(*Couldn't find file:
+ imgFitenane);
>
3Label 161 = new 3Label("The Duke", conDuke, 3Label. CENTER);
bl. setBackground(Color.LIGHT_GRAY) ;
bl setOpaque(true);
Container cp = getcontentPane();
p.add(161);
[An Inagelcon uses an java.awt-Inage object to hold the image data. You can retrieve this Image object via the Inagercon's
‘get Image() method. The Image object is used in the drawTmage() method for custom drawing (which shall be discussed later),
Most of the Swing Components supports these features:
= Text and icon,
' Keyboard short-cut (called mnemonics), e.g, activated via the “Alt key in Windows System,
' Too! tips: splay wien the mouse-pointer pauses on the component,
«= Look and fee: customized appearance and user interaction for the operating platform.
+ Localization: different languages for different locale
[Al Icomponents (such a5 3Panel, ILabel, 3TextField and 28utton) support these set methods to set their appearances and
properties:
11 Javax. suing. Iconponent
public voie setBackground(Color bgCotor)
U1 Sets the background color of this component
Public voie setForeground(Color fgcotor)
11 Sets the Foreground (text) color of this component
public void setFont(Font font)
1/ Sets the font used by this component
public void setBorder(sorder border)
11 Sets the border fon this component
public vois setPreferredsize(Oinension din)
public vote setMaxinunsize(Oinension din)
Public voie setxininunsize(Oinension din)
1/ Sets the preferred, naxinur on minimum size of this component.
public voi setOpaque(soolean 1s0paque)
1/1 oue (opaque), fill the background with background color
1/ otherwise, enable transparent background
1/ Most of the 3Conponents have default of true, except Label.
public void setTootTipText(string tool Tiplsa)
11 Sets the tool-tip message, to be displayed when the mouse-pointer pauses over the conponent.
‘Swing’s Label and buttons (AbstractButton subclasses): support both text and icon, which can be specified in the constructor or via
the setters
11 Javax.swing-2label, Javax.swing-AbstractBu
public void setText(string strText)
11 Set the text
public void setzcan(tcon defaultrcon)
11 Set the button's default icon (you can have different icons for “pressed” and “éisabled” states)
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m i42osjor2023, 19:17
public void setHorizontalAlignsent(int aLignnent)
11 Set the horizontal alignnent of icon and tes
11 Swingconstants.RIGHT, SwingConstants. LEFT, SwingConstants
public void setVerticalAlignent(int alignment)
11 Set the vertical alignment of icon and te
11 SwingConstants.TOP, SwingConstants BOTTOM, SwingConstants
public vole setHorizontalTextPosition(int textPosition)
1/ Set the horizontal text position relative to icon
11 SwingConstants RIGHT, SwingConstants.LEFT, SwingConstants
public void setverticaltextPosition(int terePosition)
1/ Sek the vertical text position relative to icon
11 Swingconstants. TOP, SwingConstants.SOTTOM, SwingConstants
dTextField supports
{GUI Programming Part2- Java Programming Tutor
ccenrer
CENTER, SwingConstants LEADING, SwingConstants. TRAILING,
11 Javax.swing. TextField, Javax.seing. Label, javax.swing.AbstractButton
public void setWorizontalAlignnent int alignnent)
11 Sev the text's horizontal alignment:
J/ TextField.RIGHT, 3TextField
11 No setVerticataLignnent as text field is single-line
Texthield.LerT, ITextield.ceNTER
DING, TextField. TRATLING
‘Swing's buttons support mnemonic (to be triggered via keyboard short-cut with alt key)
11 Javax.swing AbstractButton
public void settnenonic(int menantc)
11 Set the keyboard aneronic (i.e., the alt short-cut key).
11 Use KeyEvent.VK_exx to specify the key,
Example
This example creates 3 3Conponents: a 3Label, a
dTextField and a 3Button, and sets their
appearances (background and foreground colors,
font, preferred size and opacity). It also sets the
horizontal text alignment for the JTextField.
XO
Amport. java. amt
[&) Component Test
+ AngcrossFilenane) ;
2 import java.awt-event.*;
3 import java.net-URL;
4 import javax.swing.*;
5
6 /** Test setting Swing's 2Conponents properties and appearances */
7 @Suppresskarnings("serial")
8 public class SwingIConponentSetterTest extends JFrame (
°
10 _// nage path relative to the project root (J.2., bin)
11 private String ingcrossFilenane = "images/cross.gif";
32 private String imgNoughtFilenane = "images/nought.gif"s
a
14 /** Constructor to setup the GUI */
15 public SwingIconponentsetterTest() {
16
v 11 Prepare Inagelcons to be used with JConponents
Pry InageTcon iconcross = mull;
ry Inagetcon iconNlought = null;
20 URL imgURL = getClass().getClassLoader() .gettesource(ingCrossFilenane) ;
a if (AmgURL $= null) (
2 AconCross = new InageTcon(imguRl);
2 y else (
24 systen.err.printIn("Couldn't find file:
25 y
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m!
82‘0sio12023, 13:17
26
7
28
29
38
31
22
33
24
35
36
a7
38
39
40
a
42
a3
a4
45
48
a7
43
49
50
st
52
33
54
55,
56
37
sa
59
60
6
62
63
64
65,
66
67
68
6
70
n
n
a
™
6
76
n
78
np
80
a1
8
a
84
35
86
37
a8
{GUI Programming Part2- Java Programming Tutorial
sngURL = getclass()..getClassLoader() getResource(imgNoughtFizenne);
Sf (AngURL t= null) (
conNought = new Tnagelcon(imgURL);
) else ¢
systen.err.printin("Couldn't find #ile: " + ingNoughtFitenane);
>
Container cp = getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER, 12, 10));
// Create a JLabel with text and icon and set its appearances
ILabel label = new 2Label("Label”, iconCross, SwingConstants CENTER) ;
Jabel.setFont (new Font(Font.DIALOG, Font.ITALIC, 14));
label.setopaque(true); // needed for JLabel to show the background color
label -setbackground(new Color(294, 238, 241)); // Light blue
abel .setForeground(Color. RED); 1/ foreground text color
label. setPreferredsize(new Disension(120, 80);
label. setToolTiptext("This is a Ilabel"); // Tool tip
cp-add(1abel);
11 Create a Jeutton with text and icon and set its appearances
Button button = new 3Button(); // use setter to set text and icon
button. setText("sutton");
button. setZcon(iconNought);
button. setverticalAlignnent (SwingConstants.B0TTOM); // of text and icon
button. setHorizontalAlignnent (SwingConstants.RIGHT); // of text and icon
button, setHorizontalTextPosition(SwingConstants.LEFT); // of text relative to icon
button. setVerticalTextPosition(SwingConstants.T0P);_ // of text relative to icon
button. setFont(new Font (Font SANS SERIF, Font BOLD, 15);
button. setackground(new Color(232, 248, 248);
button. setForeground(Color-BLUE);
button. setPreferredSize(new Dinension(15@, 88);
button.setToolTipText("This is a 2Button");
button. setMnenonic(KeyEvent.VK_8); // can activate via Alt-8 (buttons only)
cp.add(button) ;
11 Create a WTextField with text and icon and set its appearances
dYextField textField = new JTextField("Text Field”, 15);
textField. setFont (new Font(Font.DIALOG_INPUT, Font.PLAIN, 12));
textfield. setforeground(Color RED);
textField. setHorizontalAlignnent(JTextField.AIGHT); // Text alignment
textfield. setToolTiprext("this is 2 JTextFielé");
cp.add(textField) ;
setbefaul tCloseOperation( JFrame. EXIT_ON_CLOSE);
setTitle(*2Conponent Test");
setLocationRelativeTo(null); // center window on the screen
setSize(see, 150); // or pack()
setvisible(true);
11 Print description of the IComponents via tostring()
system.out.printIn(label) ;
‘System.out printin(button);
systen.out.println(textFielé);
?
/** The entry main() method */
public static void main(string{] args) ¢
11 Run the GUE codes on Event-Dispatching thread for thread safety
‘Swingutilities.invokeLater(new Runnable() {
@Override
public void runt) {
‘new Swing3ComponentSetterTest(); // Let the constructor do the job
nps:iiwww3.ntu.edu sgfhomelehchualprogramminglavalida_ GUL 2m! siz‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
89 >
se Di
a}
2}
Javax.swing.2Label[, 42, 18, 126x68, aligmentX=0.0, alignnentY-8.0, borders, flag
naxinunsize=, mininunSize=, preferredsize=java.axt.Dinension(width=128, height
defaultIconeflle:.../cross.gif, disabledtcone,
horizontalslgnment=CENTER, horizontalTextPosition=TRAILING,
AconTextGap-4, labelfor=, text-JLabel, verticalAlignnent-CENTER, verticalTextPosition-CENTER]
Javax.swing.J8utton[, 271, 18, 250x80, aligneenck-d.8, alignentY=-0.5,
border=javax.swing.plaf.SorderUiResource$ConpoundsorderuIResourcetcSe2cf, Flags=424,
naxinunSizes, mininunSizes, preferredSize~java.axt.Dinension[width-150,height=3@],
defaulticoneFile:/.../nought.gif, disabledicon=, disabledselectedcon=,
nargin=javax.swing.plaf-InsetsUIResource[top#2, le¢t=i4,botton=2,right-14),
paintBorder=true, paintFocus-true, pressedzcon-, rolloverEnabled-true, rollovertcon=,
rolloverselectedtcon=, selectedicons, text=Button, defaultCapable=true]
Javan. swing. JTextField{, 331, 38, 189x21, layout=Javax. swing. plaf.basic.BasicTextUIsUpdateliandler,
alignnentX+0.0, aligneentva0.9, border=javax.swing.plaf.SorderUIResourcesConpoundsorderUIResourceisoicet,
#lags=295, naxinunsize=, sininuasizes, preferredsize=,
caretcolorssun. swing. PrintColo-UiResource[r=51, g251,b-51],
disablectextColor=javax. swing. plaf..ColorulResource[*=184,g-207,b-229], editable-true,
rargin=javax.swing.plaf. InsetsUIResource{top-2, leFt-0,bottor-8,right=0),
selectedtextColor=sun.swing.PrintcolorviResource[r=5i,g-S1,b-51],
selectionColor=javax. swing. plaf .ColorUTResource[r=184,g-207,b-223],
columnse15, columidth=7, conmande, horizontalAl ignnent=RTGHT)
‘The above clearly showed that there are many more properties that can be controled,
1.3 Display Area, Border and Insets
Display Area
You can use the following get methads to get the dimensions of the display area of a IComponent. Each component maintains its own
co-ordinates with origin (top-left corner at (0, 0), width and height. You can also get the origin (xy) relative to its parent or the screen.
public Ant getwidth()
public int getheight()
public Dirension getsize()
11 Get the current width or height of the coxponent, measured in pixels.
11 The getSize() returns width and hesght in a Dimension object.
public int getx()
public sat getv()
public Point getLocation()
11 Get the component's current origin (x, y) relative to the
J parent's (e.g., 3Panel or 3Frane) upper-left corner, measured in pixels
U1 The getLocation() returns the (x, y) in a Point object.
public Point getLocationdnscreen()
11 Get the component's current origin (x, y) relative to the screen
For example:
import java.awt.*;
Amport javax-swing-*5
1
2
3
4 public class Testsize {
5S public static void main(Stringf] ares) ¢
6 DFrame frane = new 3Frane("Display Area”);
7 Container cp = frane.getContentPane();
8 cp.setlayout(new FlosLayout());
° aButton btndello = new J8utton(“Hello”);
10 btntlello.setPreferredsize(new Dimension(100, 88));
a cp.add(btnHe20) ;
2
3 frame. setDefaultClosedperation(3Frame.EXIT_ON_CLOSE);
er Frane.setSize(300, 152); // or pack() the conponents
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m!
eia2‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
as ‘rane. setLocationtelativeTo(null); // center the application window
as Frane,setvisible(teue); V1 show 3
v
18 ‘System. out. print1n(btnHello.getSize());
1 syste. out printin(btmiello.getLocation());
2 systen.out printin(btmiello.getLocationonscreen())3
2
2 systen.out.printin(cp.getsize());
23 ‘System.out.println(cp.getLocation());
24 system, out printin(cp.getLocationdnscreen());
2s
26 System. out .printin(frame.getsize());
27 system. out printin(frane.getLecation())3
2 systen.out printin(Frane-getLocationOnscreen());
29 o
32)
Java.aet.Dimenston{width-109,height=80) _// Burton's gorsize()
Sava. ont Point [e-98, 9-5) 11 Buttons getLocation?)
Java owt Point [x-590, 9-348) 71 Burton's getLacationdnscreen()
java.awt.Dinenstonfwidth262,height=105] // ContentPane’s getsize()
java. ave. Point hee, y=e] II ConcentPane’s get.ocstion()
Java. ant Potntent99, 346) 11 ContantPane's getLocstiondascreen()
java.aet.Dinenston{width=300,hetght=150] // IFrane's getSize()
Sova ant.Point[x-490, 9-308) 11 Yerane"s getLocation()
Savaant. Point [x=890, 9-308) 1 Berane's getLocatsononscreen()
(2,8) its origin
(91,5) relative to parent (content-paney’s origin
(598,349) relativeto screen’s ori
height
Border
‘Swing supports these border types (in package javax. swing, border), which can be applied to all Components:
1. EmptyBorder: empty, transparent border which takes up space but does no drawing,
2. LineBorder: line border of arbitrary thickness and of a single color.
3. Titledsorder: with the adltion of a String tite in a specified positon and justification
4, Stroketiorder: border ofan arbitrary stroke.
5. BevelBorder: two-line bevel border.
6, SoftBevelBorder: raised or lowered bevel with softened comers.
7. BtchedBorder:etched-in or etched-out with highlightshadow.
8.MatteBorder: matte-like border of either a solid color ora tiled icon
9. CompoundBarder: compose two Borders - inner and outer.
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m! 82‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
To set a border to a JComponens, the easier way isto choose a static method from the HorderFactory class (instead of using the
constructor ofthe Border class). For example,
aPanel panel = new 3Panel();
panel -setBorder(SorderFactory..cresteLineBorder(Color.C¥AN, 15));
1/ Set border to line-border with the given color and thickness:
‘The BorderFactory clas provides these static methods to create borders
public static Border createLinesorden(Color color, [int thickness, boolean rounded])
1/ Creates a Line border with the specified color, thickness, snd corner shape.
public static Border createtnptyBorder([int top, int eft, int bottos, int right])
11 Creates an “eapty" border with the given width of the top, left, bottom, and right sides.
public static Titledsorder createritledtorder(String title)
1/ Creates 2 new titled border with the specified title,
public static Titledsorder createTstleddorder(Gorder border, [String title,
int titlesustification, int titlePosition, Font titleFont, Color titlecoler])
1/ Adds a title to an existing borden, with the specified positioning, font and color.
public static Conpoundlonder createConpoundborder( {Border outsidesorder, Border insideBorder])
11 Coeates 3 conpound border specifying the border objects to use for the outside and inside edges
WoRé: Refer to the APL
Borders ae nce into
the dsploy area of a Display area
Sonponent as astated, (2,2) including borders)
To exclude the border,
you could use the (insets. left, insets.top)
method getrnsets() to
reieve the 4 borders in
an Insets object (says Border —
snsets), and se
insets. left
insets. san me ‘
teeta border-width (getiidth()-1, getHeight ()-1)
finsets.botton to
relieve the width of the 4 borders. For example,
11 Continue from previous exanple
Insets insets = frane.getinsets();
systen.out .printin(insets);
U1 Java.ant. Insets{tope36, LeFt=9, botton9,right=9)
int realdicth = frane.getiidth() - insets.left ~ insets.cighty
int realbeight = frane.getHeight() - insets.top - insets.botton;
systen,out.printIn("real width = "+ realhidth); —// real width = 282
systen.out-println(*real height = "+ realleight); // eal heignt = 205
Example
This example ilustrates the display area, border and the various dimension
1 import java.awt.*;
2 import Javax.swing.*;
3
4 [JB Swing application inherits frox top-level container javax.swing. rane
5 public class TestoisplayAreatndsorder extends 2Frame {
6 /** Constructor to setup the GUI */
7 public TestDisplayAreatnddorder() {
3 Container cp = getcontentPane();
° cp.setLayout(new FlowLayout());
10
a BTextArea comp = new 3TextArea(1®, 25); // row and columns
2 conp.setBackgroune(new Color(20@, 208, 288));
a conp.setForeground(Color BLUE);
nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m! eua2osjor2023, 19:17
14
3
a6
v
18
»
20
a
2
23
24
23
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
a
2
43
4
4s
46
a7
48
49
50
st}
{GUI Programming Part2- Java Programming Tutor
LS) Appearance and Border
conp. setBorder(BorderFactory. createLineBorder(Color.CYAN, 15))
J] set border to Line-border with the given color and thickness
conp.setPreferredSize(new Dinension(35@, 200);
p.add(conp)
setDefaul tcloseOperation( Frame. EXIT_ON_CLOSE);
setTitle(“Appearance and Border");
setSize(40e, 320);
setVisible(true);
StringBuffer msg = new StringBuFfer();
‘esg.append("Width = " + conp.getkidth());
‘asg.append("\oHeight = " + comp.getHeight());
sg. append(“\nOrigin-x = " + comp.getx())3
‘ese.append("\nOrigin-¥ =" + comp. getY());
‘ssg_append("\nOrigin-x (on screen) = * + conp.getLocationOnscreen().x);
‘asg.append("\nOrigin-¥ (on screen) = * + comp.getLocationonscreen().¥)
Insets insets = comp.getInsets()3
‘asg.append("\nInsets (top, right, bottom, left) =
‘+ insets.top + ",7 + insets.right + 7," + insets-botton + "," + insets. left);
‘asg.append("\nReal Width = "+ (comp.getWidth() - insets.left - insets.right));
‘isg.append("\nReal Weight =” + (conp.getHeight() - insets. top - insets.botto=));
comp. setText(nsg. tostring()
?
[9 The entry eain() method */
public static void main(String[] args) ¢
11 Run the GUI codes on Event-Dispatching thread for thread safety
‘SwingUtilities. invokeLater(new Ruanable() {
SOverride
public void run() (
new TestDisplayareatndferder(); // Let the constructor do the job
>
ys
You can position your main application window (2Frane), or top-level container, on the screen, via
1/ Set wethods (in java.avt window)
11 (Xs ¥) specifies the origin (top-left corner) of the window on the screen
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m a2‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
public void setsize(int wideh, int height)
public voie settecation(int x, int y)
public void setBounds(int x, int y, int width, int height)
public void setsize(Dinension dir)
Public voie settocation(Point origin)
public voié setBounds(Rectangle r) // 20K 1.6
// The associated get methods (In Java.ant.Conponent) are:
public int getwidth<)
public int gethetght()
public int getxt)
public int getv()
public Dirension getsize()
public Point getLacation()
public Rectangle getBounds()
J) No setx(), set¥(), setwidth(), setHeight<)
You can get the screen size via static method Toolkit .getdefaultToolkit().getScreensize(). For example,
inension cim = Toolkit.getbeFaultToolkit().getScreensize(); // Get the screen dinension
ant sereenkicth = din.widthy
Ant screenteight = din-heigth;
You can also run your application in full-screen mode (with or without decorations such as title bar), instead of window-mode. Read
“Swing How-To"
‘A quick way to center your application on the screen isto use setLocationRelativeTo(nul1)
setSize(WINDOM_MIOTH, WINDOW HEIGHT); // or pack() the components
setLocationtelativeTo(null);// center the window on the screen
11 shall be run after setsize()
setvistble(true); 11 show 3
1.5 Text Components: JTextField, JTextArea, JEditorPane
‘Swing provides 6 text components, as shown in the
above clas diagram, All text components extends from object |
TTextConponent.
1. aTextFteld sPasswordField, Component |
HFornattedTextField: For displaying only one —_
line of eatable text, Like burtons, they tigger
Action vent when user hits the "enter key. Container |
2, sTextarea: Plain text ares for displaying multiple z
lines of ecitable text, unformatted. All the texts are a
Inthe same font aiaaia
3
‘JEditorPane, ITextPane: A styled textarea which
an Use more than one font. They support \diexttommonent,
embedded images and embedded components
JEditorPane can load HMTL-formatted text from
URL BTextField) JTextArea) JEditorPane
|aroraattedtextrield) JPasswordField| 3TextPane
Example: JTextField, 3PasswordField, JFormattedTextField, and 3Textarea
This example illustrates single-ine ITextField, IPasswordField, JFormattedField, and multiline ITextarea wrapped inside an
2Scrol Pane.
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m! roe‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
[Eltacioeomt tens
Tee:
eau
ee aes
4 Traci e.4"plom able tat component
whickmeans hat although can dpa ect aay
font all ef ths tx tho samen
1 import java.awt.*;
2 import java.aut.event.*
3 import javax.swing.*5
4
5 /** Test JTextField, IPasswordField, JFormattedTextField, JTextarea */
6 GSuppresswarnings(*serial")
7 public class JTextComponentdeno extends 3Frane {
8
9 /] Private variables of the GUI conponents
10 —-‘YextField tField;
11 —-3PasswordField pwrield;
32 Wextares tarea
12 HForsattedTextField formattedField;
4
15 /** Constructor to set up all the GUI conponents */
16 public JTextConponentdeeo() {
v {1 3anel for the text fields
8 dPanel tfPanel = new JPanel(new GridLayout(3, 2, 18, 2));
ce ‘t#Panel setBorder(BorderFactory.cresteTitledBorder("Text Fields: "));
20
a 11 Regular text field (Row 1)
2 tfPanel.add(new JLabel(" 3TextField: “));
23 tField = new ITextField(16);
2a ‘tfPanel..add(tFiele);
23 tield.addActionListener(new ActionListener()
26 override
a7 public void actionPerformed(Actionevent e) ¢
8 ‘tarea.append(*\nYou have typed " + tFielé. getText());
29 >
30 Di
a
32 11 Password Field (Row 2)
33 tfPanel.add(new JLabel(" 3PasswordField: *));
34 paFielé = new JPasswordField(18);
as tfPanel add (pwField);
36 PaField.addActionListener(new ActionListener() ¢
a7 Goverride
38 public void actionPerformed(Actionevent ) <
39 ‘tarea.appenc("\nYou password is " + new String(puField.getPassword()));
40 y
a Ds
a2
a 11 Formatted text field (Row 3)
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m! me‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
4a tfPanel.add(new JLabel(" 3ForaattedTextFielé"));
4s FormattedField = new JFormattedTextField( Java.util.calendar
46 sgetInstance().getTine())5
a7 tfPanel add (formattedField);
48
49 11 Create a 3TextArea
50 threa = new JTextArea("A JTextArea is a \“plain\" editable text component, "
51 4 "which means that although it can display text
52 4 “in any font, all of the text is in the sare font.“);
33 tarea.setFont(new Font("Serif", Font.ITALIC, 13));
sa threa-setLineWrap(true) ; U1 wrap Line
ss tarea.setwrapstylesiord(true); // wrap Line at word boundary
56 ‘threa.setBackground(new Color(204, 238, 281); // light olue
37 11 Weap the 3TextArea inside a 3Scrol1Pane
58 yscrollPane tAreascrol1Pane = new 3ScrollPane(tarea);
59 ‘tareaScrolIPane. setBorder(BorderFactory.createEmptyBorder(1®, 18, 18, 10);
60 ‘threascrol Pane. setVerticalScrol18arPol icy(3Scrol1Pane. VERTICAL_SCROLLBAR_ALWAYS);
6
6 11 Setup the content-pane of 3Frare in BorderLayout
3 Container cp = this.getContentPane();
64 cp-setLayout(new BorderLayout(S, 5));
65 ep.add(tfPanel, BorderLayout .NORTH) ;
66 p.add(tAreaScrol Pane, BorderLayout..CENTER) |
67
68 setDefaul tcloseOperation( JFrame. EXIT_ON_CLOSE);
ea setTitle("JTextConponent Deno");
70 setsize(350, 350);
n setVisible(true);
Rm}
B
74 J#* The entry wain() method */
75 public static void main(String] args) {
78 1/ Run GUI codes in Event-Dispatching thread for thread safety
7 SwingUtilities. invokeLater(new Runnable)
7 override
nm public void run() (
80 new JTextConponentdeno(); // Let the constructor do the job
at >
2 »
3}
a}
aPasswordField
Use getPassword() to get the password entered in a char[]. TODO: Security Issues]
aFormattedTextField (Advanced)
ToDo}
JTextArea wrapped in a JScrol1Pane
Its common to wrap a 3TextArea inside a 3Scrol1Pane, so as to scroll the text area (horizontally or vertically). To do so, allocate a
2Scrol1Pane with the ITextArea as the argument.
JTextarea tarea = new ITextArea(...); // Allocate ITextarea
3Scrol1Pane tAreascroliPane = new 3Scrol1Pane(tArea); // Allocate IScrolPane which wraps the Textarea
‘tareaScrollPane.setverticalscrol8arPolicy(...); 11 Configure vertical scroll bar
‘tareaScrollPane.setHorizontalScroliBarPolicy(...); // Configure horizontal scroll bar
JTextArea’s Properties
You can replace the document, or append or insert more text
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m! rae‘0si012023, 13:17 {GUI Programming Part2- Java Programming Tutor
public void append(string str)
1/ Append the str to the end of the document
public void replaceRange(String str, int startPos, int endPos)
1/ Replace with the str from startPos to endeos position
public void insert(string str, int pos)
Ui Ingert the str after the specified position
JEditorPane as HTML Browser
You can use JEditorPane to display an HTML document (but no CSS and JavaScript). Again, itis common to wrap a JEditorPane
inside a 3Serol1Pane. For example,
dEditorPane editorPane = new JEditorPane(); // allocate a editorPane
‘editorPane, seteditable(false);
ty (
1/ Form a URL and display the HTML page on the editor-pane
URL UPL = new URL("http://am3 mtu. edu. sg/hore/ehchva/progranming/ index.htm!
editorPane.setPage(url);
} catch (MalformedutLexception e) {
e.printstackTrace();
} catch (IOException e)
e.printstackTrace();
>
11 weap the 1EéitorPane inside 2 IScrol1Pane
IScrollPane editorscrollPane = new IScrol1Pane(editorPane);
‘editorscroliPane. setVerticalScrol8arPol icy(3Scrol1Pane. VERTICAL SCROLLBAR_ALMAYS);
setContentPane(editorSeroliPane);
JTextPane (Advanced)
dTextPane is used for formated styled text display; whereas 2TextArea is used for plain text display. Although you can set the font
and style for 2TextArea, all the text is display in the same font. In 3TextPane, you can set different fonts and styles for different
sections of text
You can use 3TextPane for to develop an editor (such as NotePad or NotePads +) with ciferent sections of text displayed in diferent
fonts and colors.
Example: See Swing Tutoria’s “Text Component Features”. This is an excellent example that illustrates many features and concepts,
Text Component API: It provides many features, from cut and paste to changing the selected text. See Swing Tutorials “Text
‘Component API
Read: Swing Tutorials "How to Use Buttons, Check Boxes, and Radio Buttons".
‘A.user can click a button (or a menu item) to trigger a specific action. Swing supports mouse-less operations, where user could use a
keyboard short-cut (called mnemonic) to activate the action,
Buttons and menu-items are inherited from AbstractButton, as shown in the class diagram.
You could place a text string (called buttons label) as well as an icon on the button, You could use different icons for different button
states: defaultTcon, disabledtcon, pressedicon, selectedIcon, rollovercon, _disabledselectedtcon,
rolloverSelectedtcon. The defaulticon can be set via the constrictor or settcon() method. The other icons can be set via
sevrextcon() methods. You can set the alignment of text and button via settorizontalAligment() and
setVerticalAligrment() methods. You can sat the position ofthe text relative to the ion va setHorizontalTextPosition() and
setvertical TextPosition().
‘Swing supports many type of buttons.
Command Buttons: JButton
(lick to fires an ActionE vent to allits registered ActionListeners,
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m!
rae‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
Toggle Buttons: JRadioButton, ICheckBox, )
aToggleButton Object
Toggle buttons are two-state buttons: SELECTED or a
DESELECTED. Component |
For radio button, you can choose none or one among the
group. 3RacioButtons ate ‘typically added into a
Container
Buttoncroup to ensure exclusive selection. RadioButton —
fires TtenEvent to iis TtesListeners. It also. fires
ActionEvent to its ActionListeners. Both TtenEvent Component |
and ActonEvent can be used. a
For chuckboes, you can chose none or mote among the 1 —
croup. iGucidaxes fre Teencient’ at wall oe | WMMUGEBGRa) —\stneateiaben,
ActLonEvent. We yplally use TeenEvent as we may ned
to distinguish between emstates of SELECTED and aa! ae
beseuecren, \aauisces! |
The Ttentistner (of tenGvent) decks one abstract oT
method itenstateChanged(Ttenfvent ©) checkiox) IRadiotutton| | Menu
3ComboBox
2comboBox can be used to provide a drop-down menu. It supports single-selection and muliple-selection. ComboBox receives a
Object array (typically a String array), which provides the items in the drop-down list. 3ConboBox fires TtenEvent. We could use
3ConboBox's getSelectedindex() to get the index of the selected item: or getSelectedrtem() to get the selected Object,
ComboBox also fires ActonEvent.
Example on JButton, IRadioButton and 3ComboBox
In this example, we shall modify our counter application to (i) swing Counter wth RadioButton & Combobox = =I) oe
Include two radio buttons for specifying counting up/dawn, and 2
combo-box to select the count-step size, — FO we Ones weit Sova
1 import java.awt.*;
2 import java.awt-event.*;
3 import javax. swing.
4
5 /** Counter with 3RadioButton and IConbo8ox */
6 @Suppresskarnings(*serial")
7 public class SwingcounterRadioConbo extends IFrame {
3 private TextField tfcount;
9 private int count = 9; // counter's value
10 private boolean countingup = true; // counting up or down
11 private int step = 1; // increnent step size
2
13 /** Constructor to setup the UI */
14 public SwingCounterRadiocondo () {
rey Container cp = getContentPane();
16 ep. setLayout(new FlosLayout());
v
18 11 Create Jhabel and TextField
cy p.add(new ILabel ("Counter"):
20 #fCount = new JTextField("@", 5)3
a tfCount -setEditable(false);
2 tfCount .setorizontalAl ignment (2TextField. RIGHT) ;
23 ep.add(tfcount) 5
24
Fey 11 Create JRadioButton for counting up and down
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m!
rasa‘0sio12023, 13:17
26
7
28
29
38
3”
22
33
24
35
36
a7
38
39
40
a1
a2
a
44
45
48
a7
48
GUI Programming Pan 2 Java Programming Tutorial
DRadioButton rbUp = new JRadioButton("Up”, true);
Up. setiinenonic(KeyEvent..VK_U);
cp.add(rbup)
roUp.addActionListener(new ActionListener) {
override
public void actionPerforned(Actionévent e) {
‘countingup = true;
Di
RadioButton rbDoun = new 3RadioButton("Doun'
rreDown.setNnenonic(KeyEvent.VK_D);
p.add(rbdown) 5
rPoDown.addActionListenen(new Actionlistenen() {
@override
public void actionPerformed(Actionévent e) {
‘countingUp = False;
true);
De
11 Setup a ButtonGroup to ensure exclusive selection
ButtonGroup btnGp = new ButtonGroup();
btngp.add(rbUp);
bbtngp add(rb00un) ;
11 Create IConboBox for setting the count step size
add(new JLabel("step:"));
Final Integer(] steps = (1, 2, 3, 4, 5); // auto-upcast
Final 3ConboBoxcrnteger> conbocount = new IComboBox(steps);
conbocount .setPreferredSize(new Dinension(6®, 20);
cp.add(conbocount) ;
conboCount .addItem(istener(new ItemListener() {
Goverride
public void itenstatechanged(Itenevent e) {
Af (e.getStatechange() == TtenEvent SELECTED) {
step ~ (Integer)conboCount .getSelectedrten();
,
De
11 Create 3Button for “Count
dutton btncount = new JButton("Count);
btncount. setPinemonic(KeyEvent.VK_C);
p.add(btncount);
btncount.addActionListenen(new ActionListener() {
@override
public void actionPerforned(actionévent e) {
Af (countingup) (
count += steps
} else {
steps
?
tfCount.setText (count +
De
setbefaul tCloseOperation( JFrame. EXIT_ON_CLOSE);
setTitle("Swing Counter with RadioButton & ComboBox");
setsize(48e, 100);
setvisible(true);
?
J** The entry main() method */
public static void main(string{] args) {
11 Run the GUT codes in the Event-Dispatching thread for thread-safety
hips: ww. ntu.od sghhomeiehchualprogramminglavalJ4a_GUL_2.hinl
1542‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
89
30
31
92
3
94
9
96
‘SwingUtilities. invokeLater(new Runnable() {
Goverride
public void run) (
new SuingCounterRadioCorbo(); // Let the constructor do the Job
>
ys
Example on 3RadioButton, JCheckBox and ComboBox
In this example, we have two groups of radio buttons: one group to set the
horizontal alignment of the JLabel, and processed via ItesEvent; another
oct pament
‘group sets the vertical alignment and processed via ActSonEvent. Cun
32
33
34
35
36
37
Wren
akon
ore aagamont
Ow = wa
import java.awt.¢;
import java.awt .event.*;
import java.net. URL;
import Javax.swing-*5
/** Test RadioButton, ICheckBox and ICosbo30x */
(@SuppressWarnings(*serial")
public class ButtonConboBoxbeno extends JFrame {
// private variables of GUI components
private JLabel 1biForrest;
private String ingcrossFilenane
private String 1blText = "Cross'
private Icon iconcrass;
“inages/cross.gif";
private 2RadioButton rbLeft, rbcenter, roRight, rbTop, rbMiddle, rbBotton;
private 2heckiox cbText, cbIconj
private IConbosox corbocolors
/** Constructor to setup the UI components */
public ButtonConboboxdeno() {
1 Create a ILabel with text and Seon for manipulation
URL dngURL = getClass() .getclassLoader() .getResource(ingcrossFilenane);
Af (eguaL I= mul) ¢
Aconcross = new Inagercon(ingURL);
} else {
Systen.err.printLn(“Couldn't find file: ~ + ingCrossFilenane) ;
y
IblForTest = new JLabel(blText, iconCross, SwingConstants.CENTER);
IblForTest.setopaque(true);
IblForTest .setBackground(new Color(204, 238, 261));
AblForTest. setForeground (Color. RED);
Lb1Forrest.setFont(new Font(Font.SANS_SERIF, Font. ITALIC, 18))3
JJ Create radio buttons for setting horizontal alignment of the 2Label
rbleft = new JRadioButton("Left");
ebLeft.setiinenonic(KeyEvent.VK_L);
rbCenter = new JRadioButton("center", true); // selected
nps:iiwww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m
1642‘0sio12023, 13:17
38
33
40
aa
a2
3
44
45
46
a7
48
49
se
52
52
33
54
56
37
sa
53
6@
61
62
63
64
65
66
6a
63
7
a
2
1
75
76
78
8@
82
82
83
a4
8s
86
87
88
89
98
oa
92
3
95
96
7
98
99
300
GUI Programming Pan 2 Java Programming Tutorial
rbcenter. settineronic(KeyEvent .VK_C);
rbRight = new IRadLoButton("Aight
rbRight.set¥nesonic(KeyEvent.VK_R)5
// Put the radio buttons into a ButtonGroup to ensure exclusive selection
ButtonGroup btnGroupl! = new Buttonsroup();
btnGroupH. add(rbLeft);
benGroupH. add(rbRight);
btnGroupl. add(rbcenter) ;
/J Set up 2 3Panel to hold all radio buttons
3Panel pniRbtnl = new JPanel(new GridLayout(1, @)); // single row
pniRbtnH.ada(rbLeft);
pninbtnH.add(rbcenter);
pniRbtaH.ada(rbRight);
PnIRbtni. setBorder(BorderFactory.createTitledsorder(*Horizontal ALignment)) ;
J] & YenListener for 311 Radio buttons
TtenListener Listener = new ItenListerer() (
(override
public void itenstatechanged(rtentvent e) (
if (e.getStatechange() == Itentvent. SELECTED) {
if (e.getSource() == rbLeft) {
Ib1ForTest. setMorizontalALignnent(Swingconstants.LEFT);
) else if (e.getSource() == rbcenter) {
Ib] ForTest.setHorizontalALignnent (SwingConstants.CENTER) ;
} else if (e.getSource() == rbRight) {
AblForTest.setHorizontalAlignment (SwingConstants RIGHT) ;
y
x
h
rbLeft addItentistener(Listener);
rbcenter.addrtertistener(Iistener);
rbRight addi teal istener(listener) ;
1 Create radio bustons for setting vertical alignnent of the ILabel
rbTop = new JRadioButton("Tos");
rbTop.settinenonic(KeyEvent.Vx_1);
rbliiddle = new IRadiobutton("Middle”, true); // selected
rbMiiddle. setsneronic(KeyEvent..VK_M) 5
rbsotton = new 2Radiobutton("Botton”);
rbsotton. settneronic(KeyEvent..VK_B);
JJ Put the radio buttons into a ButtonGroup to ensure exclusive selection
ButtonGroup btnSroupV = new SuttonGroup();
benGroupV. add(rbTop)s
benGroupv.add(rbMiddle);
btnGroupV.add(rbsotton) ;
JJ Set up a JPanel to hold all radio buttons
3Panel pnikbtnV = new JPanel(new GridLayout(1, @)); // single row
pnirbtnv.ada(rbTop) ;
pniRbtnV.ada(rbitiddie);
palrbtnv.add(rbBotton);
PniRbtnv. setBorder(BorderFactory.createTitledBorder(*Vertical Alignment")) 5
J/ Radio buttons also Fire Actiont vent
rbTop-addactionl istener(new Actionlistener() {
@override
public void actionPerformed(ActionEvent e) {
AblForTest.setVerticalAlignnent(SwingConstants.10P);
y
Ds
rbiddle.addActionListener(new ActionListener() {
@override
public void actionPerformed(ActionEvent e) {
hips: Www. ntu.od sghhomeiehchualprogramminglavalJ4a_GUL_2.hiel vise‘0sio12023, 13:17
ae
302
103
108
105
106
207
108
309
ue
a
uz
a3
ue
us
16
7
us
9
ne
aa
a2
223
a4
125
26
a7
128
29
ae
at
132
13
4
135
136
37
ne
139
140
aa
142
a3
u
145
M6
147
ua
149
150
asi
152
353
154
155
356
157
358
159
360
ae
162
363
{GUI Programming Part2- Java Programming Tutor
AblForTest.setverticalAlignnent (SwingConstants.CENTER) ;
y
Ds
bBotton-addactionListener(new ActionListener() {
override
public void actionPerforned(ActionEvent e) {
AblForTest.setVerticalAlignsent(SwingConstants. BOTTOM) ;
y
Ds
11 Create checkboxes for selecting text, icon, or both, on none
btext = new Ichecksox("Text®, true); // selected
cbText.setvinenonic(KeyEvent .VK_T)3
cbteon = new ICheckBox("Teon", true); // selected
cbIcon, setvinenonic(KeyEvent .VK_I);
cblcon.setselected( true);
11 Set up a Wane to hold all checkboxes
Panel pnicbox = new 3Panel{new Gridtayout(@, 1)); // single column
prichox.add(ebrext);
pnichox.add(cbicon);
11 Checkboxes Fire Teentvent. Use an anonysous inner class as TtepListener
cbText.addttentistener(new Itentistener() <
@override
public void stenstatechanged(rtenevent e) (
1/ Need to handle both SELECTED and DESELECTED
AF (e.getStateChange() == Ttentvent.SELECTED) (
AblForrest.setText (IbLText);
p else ¢
LblFortest.setText(
y
y
Ds
cbIcon.addrtenlistener(new TtemListener() {
eoverride
public void itenstatechanged(Itentvent e)
1/ Need to handle both SELECTED and DESELECTED
if (e.getStatechange() == Ttentvent.SELECTED) {
IblForTest.setIcon(iconCross) ;
y else ¢
IblFortest.seticon(nul1);
»
y
Ds
JJ Create conbobox (drop-down menu) for the foreground colon of the JLabel
Steing[] strColors = "Red", "Blue", “Green,
“cyan”, "magenta", "Yellow", "Black"};
Final Colos{) colors = (Color.RED, Calor.BLUE, Color.GREEN,
Color.c¥AN, Color.MAGENTA, Color.YELLOK, Color.BLACK};
conboColor = new IConbobox(strColors);
conbocolor.additemListener(new TteaListener() {
@override
public void itemstateChanged(Itentvent e) {
Af (e.gotstatechange() == TtonEvent. SELECTED) (
IbiForTest. setForeground(colors{conboColor. getSelectedindex()]);
»
y
Ds
JJ Set up a 3Panel for the combobox
Panel palConbo = new 2Panel(new FlowLayout ());
pnlCosbo.add(conboColor);
1/ Set up the content-pane with BorderLayout and adds the panels
nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m!
saa‘0si012023, 13:17 {GUI Programming Part2- Java Programming Tutor
et Container cp = this. getContentPane()s
165 cp. setLayout (new BorderLayout());
166 cp.add(lolFortest, Sorder\ayout. CENTER);
167 cp.add(pniRbtnk, BorderLayout.NORTH) ;
168 ‘p.add(pnIRDtnv, Border ayout. SOUTH):
169 ‘p.add(pnicoox, order ayou. WEST);
ve cp.add(pniconbo, BorderLayout. EAST);
m1
im setdefaultCloseoperation(3Frane.€XzT_ON CLOSE)
13 setTitle("button and Corbotox Deno");
v4 setsize(420, 208); // or pack() the conponents
v5 setLocationtelativeTo(nv1};
176 setvisible(true);
177 ?
ve
179 /** The entry main() method */
188 public static void main(string[] args) {
ae 1/ fin GU codes in the Event-Dispatening thread for thread safety
182 ‘SwingUtilities.invokeLater(new Runnable() {
183 public void run() {
184 new ButtonConboBoxbena(); // Let the constructor do the job
185, +
186 Da
187 ?
188}
1.7 Menu-Bar: JMenuBar, JMenu, JMenuItem
The menubar sat the same level as the contentpane
(0f the top-level container 3Frame), It is set via the Object
PFrane's set Menu8ar() method Gimilar to —z
setcontentPane()) ae
To create a menv-bar, construct 2 3MenuBar. A meni —sz
bbar (2MenuBar) contains menu (2Menu). A menu .
contains menuitem (JMenurten). JMenuTten is a Container
subelass of AbstractButton, similar to 3Button a
aMenuTter fires Action vent upon activation to all its poosnareits
tegistered ActionListener. oe
Example 3MenuBar AbstractButton
this ([5 Test MenuBar i
ei Ape “JMenuttem| | JButton | JToggleButton!
oo 1
menu-bar contains 2 menus (Menu-A and Menu-8). wer iheskeos| \ghedigbuttos
Menu-A contains 2 menu-items (Up and Down). Menu-
Bhas 1 menu-item (Reset)
import java.awt.*;
import java.awt event.
Amport javax-swing-*;
/** Testing menu-bar of 3Frane */
public class Test3menuBar extends JFrame {
dTextFielé display;
int count = @;
0
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m!
1912osjor/2023, 19:17
a
2
B
ua
a5
16
vv
8
2
20
a
2
23
24
25
26
27
28
29
30
a1
32
3
34
35
36
37
38
39
48
a
a2
a
4
45
46
a7
48
49
50
st
32
33
54
55
56
37
se
59
60
oa
62
63
64
65,
66
7
6
6
7”
n
n
a
{GUI Programming Part2- Java Programming Tutor
/** Constructor to setup the GUI */
public TestaMenuBar() {
17 menu-bar contains menus. A menu contains menu-itens (or sub-Menu)
2MenuBar menubar; // the menu-bar
Menu menu; 77 each menu in the menu-bar
dMenutten senurten; // an iten in a menu
menuSar = new 3MenuBar() ;
17 First Menu
‘menu = new Menu("Menu-A");
‘menu. setvinenonic(KeyEvent.VKA); // alt short-cut key
menuBar.add(menu); // the menu-bar adds this menu
‘menuten = new JMenuzten("Up", KeyEvent .VK_U);
‘wenu.add(menuttem); // the menu adds this item
smenurten.addactionListener(new ActionListener() (
override
public vold actionPerformed(Actionevent e) ¢
+ecount
Gisplay.setText(count +");
y
De
smenulten = new JMenuztem("Down”, KeyEvent.VK_b);
smenu.add(menurtem); // the menu adds this item
menurten-addactionListener(new ActionListener() {
override
public void actionPerformed(Actionevent e) ¢
=-counts
display. setText(count +”
y
ye
11 Second Menu
‘menu = new Menu("Menu-8");
‘menu, setvinenonic(KeyEvent .VK_8); // short-cut key
menuar.add(menu); // the menu bar adds this menu
‘nenulten = new 3Menuzten("Reset”, KeyEvent.K_R)s
‘menu.add(menurtem); // the menu adds this item
menulten.addActionListener(new ActionListener() {
Goverride
public void actionPerformed(Actionevent e) ¢
count = 6;
Gisplay.setText(count +");
y
De
setIMenuBar(menuBar); // "this" 2Frane sets its menu-oar
Container cp = getcontentPane();
cp.setLayout(new FlosLayout());
display = ne JTextField("0", 26);
cp.add(display)
setbefaultCloseOperation( JFrame. EXIT_ON_CLOSE);
setTitle(“Test MenuBar");
setSize(30@, 100);
setVisible(true);
?
1° The entry main() method */
nps:iiwww3.ntu.edu sgfhomelehchualprogramminglavalida_ GUL 2m!
20142‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
74 public static void main(String] args) {
8 11 Run the GUT codes on the event-dispatching thread for thread safety
78 SwingUtilities.invokeLater(new Runnable() {
7 @override
7 public void runt) ¢
nm new TestIMenuBar(); // Let the constructor do the job
30 »
a »
2}
3}
1.8 JOptionPane: Interacting with the User
‘The javax. swing. JOption?ane provides standard pre-built diglog boxes to interact with user for both input and output. To create a
dialog box, use one of the static methods JoptionPane. showXxxDialog()
11 Prompt for user input
public static String showinputDialog(abject message, [Object {nittatsetect onvatue)}
public static Object shouInputDlalog(component parentCompanent, Object message,
[String title], [int messageType], [Zeon tcon], [ObJect{] options], [Object tnitiatvatue])
11 asks 3 confirming question (yes/no/cancel)
public static int showConfireDialog(conzonent parentConponent, Object message,
[String title], [int optiontype], [int messagetype], [Icon icon])
11 Display a eessage
public static void showessageDialog(Conponent porentComponent, Object message,
[String tele], [int messogetype], (Icon {con])
1/ Support ali Features of the above three methods
public static int showoptionDlalog (Component parentComponent, Object message,
String title, int optionlype, Int messagetype, Icon ican, Object{] options, object intttalvatue)
11 Conponent parentConponent: parent of this dialog box, for poisitioning.
1] Tf null, centered on the screen
1/ Object message: the nessage, typically a String.
1/ String title: the title for the dialog box
1/ int messageType: the style of the message,
11 WOptionPane. instr);
° JoptionPane.showessageDialog(null, “Display 2 message (returns void)!",
1 "Message Dialog”, JOptionPane, PLAIN MESSAGE
u {nt answer = J0ptionPane.showConfiraDialog(null, “Ask for confirmation (returns an int)",
2 “Confirm Dialog”, JOptionPane. YES_NO_CANCEL, OPTION);
2 switeh (answer) {
a case J0ptionPane.YES_OPTION:
15 systen.out printin("You clicked YES"); breaks
16 case JoptionPane.No_OPTION:
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m! 22‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
uv
Py
9
20
systen.out.printin("You clicked NO"); break;
case JOptionPane.CANCEL_OPTION:
systen.out.printin("You clicked Cancel"); break;
coinooeo
e Eee een
Ges) [cme
Take note that input dialog returns the String entered by the user, confirm dialog returns an int (JOptionPane.YES_OPTION,
NO_OPTION, CANCEL_OPTION}; message dialog returns void, Furthermore, you can use JOptionPane directly under main() to promot
user for input, similar to text-based input via Scanner.
Example: Prompting User for Input with Validation
0
a
2
a
4
rey
16
vv
Py
19
20
(S) Testinput Dialog |= EI] 3S |
Amport java.ant.*5
import java.awt.event.*;
Anport Javax.swing.*5
public class InputDialogwithvaLi¢ation extends JFrame (
DTextFielé tfDisplay; // to display the nunber entered
1° Constructor to setup the GUI components */
public InputDialogwithValidation() {
Container cp = getContentPane();
ep. setLayout(new FlosLayout());
tfoisplay = new ITextField(10) 5
tfoisplay.setéditable(false);
cp.add(tOisplay);
aButton btn = new JButtont
ep.add(ben);
btn. addactionListener(new ActionListener() {
override
‘Input")5
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m!
2242‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
a public void actionPerformed(Actionevent e) ¢
2 boolean validinput = false; // for input validation
2 int nurberins
4 String inputStr = JOptionPane.showrnputDialog("Enter a nunber [1-3]:
25 60 <
26 try (
27 hunberin = Integer.parsernt (énputstr) ;
28 } catch (NumberFormatexception ex) {
29 unberIn = -1; // input triggered NunberFormatexception, set to invalid
30 x
a1 Af (numbertn <1 || numbertn > 9) {
32 AnputStr = JOptionPane.showInputDialog("Invalid nunner! Enter a nusber [1-9]: ");
3 ) else {
34 JopticnPane.showessageDialog(null, “You have entered * + nunberin);
35 validinput = true;
36 >
37 } while (Ivalidtnput); // repeat if input 1s not valid
38 tAbisplay.setText(numberin + "*);
39 »
48 De
a1 ‘setDefaul tcloseOperat ion(EXIT_ON_CLOSE);
a2 setsize(300, 100);
43 setTitle(*Test Input Dialog");
4 setVisible(true);
3}
48
47 /** The “main” entry method */
48 public static void main(stringl] args) {
49 11 Run the GUT code on the Event-Dispatching Thread for thread safety
50 Javax. swing. Swingutilities invokelater(new Runnable() {
st public void run() (
32 ew InputDialogwithvalidation(); // Let the constructor do the job
33 >
54 Di
3}
36}
2. Pluggable Look and Feel
‘Swing supports the so-called "pluggable look and feel (plat) for its 3Components. The "look" refers to the appearance of the widgets
(2Conponent); while the “feel” refers to how the widgets behave (eg, the behaviors of mouse-clck for the various mouse-buttons).
“Pluggable” refers the ability of changing the look and feel at runtime,
You can choose to use the default Java look and feel, the native system's look and feel (Windows, Linux, Mad), oF the newer cross~
platform Nimbus look and feel,
Pluggable look and feel is supported in Swing's components by separating the components into two classes: 3Component (in package
Javax. swing) and CoeponetUT (in package javax.swing.plaf), The CosponetU, called Ul delegate, handles all aspects relating to
look and feel. Nonetheless, you shall not interact withthe Ul delegate directly.
‘These look and feel are supported (in packages javax. swing. plaf and javax. swing. plaf.*)
1.Java Look and Feel: Also called CrossPlatforalookAndFeel, or Metal LA. The default LF which provides the same look and
feel across all the platforms,
2, System Look and Feel: the LAF of the native system (eg, Windows, Linux, Mac).
3. Nimbus Look and Feel: the newer cross-platform look and feel released in JDK 1.6 update 10.
‘nps:iiwww3.ntu edu sgfhorelehchualprogrammingjavalida_GUL_2himl 2a‘01012023, 13:17 {GUI Programming Part 2 - Java Programming Tutor
[2] Nimbus Look o
Counter 9] © Up O dom step: (ix) [ Count
WF
‘The JEC demos (included in JOK deme) “SwingSet2" and "SwingSet3" show the various LFS.
2.1 Setting the Look and Feel
You need to set the Look and Feel as the frst step in your GUI construction. There area few ways to set the Look and Feel
Via UIManager. setLookAndFeel()
You can use the static method UIManager. setLookAndFeel (String className) to set the look and feel
= You can either use the static method ~—_UrManager. getCrossPatforaLookindFeelClassNane(),
Utmanager. getSystenLookAndFeelClassNane() to get the classname sting for Java FEAF and Native System LAF; or
= Use the actual classname string suchas “Java
swing.plaf.netal.MetalLookAndFeel” (for Java LA,
*con.sun.Java.swing.plaf windows WindowsLookAndFee” Windows Lan,
"Javax. swing. plaf.ninbus .NimbusLookAndFeel" (Nimbus Lary and
“con.sun. java. swing.plaf.motif.Mot:ifLookandFeel” (Motif L&F)
For example,
1) Set the UL manager (shall be the first step of the GUL construction)
try ¢
11 Set to cross-platform Java Look and Feel (also called “Ketal”)
UiManager.setLaokAndFeel(UIManager. getCrossPlatforaLookAndFeelClassNane());
} catch (UnsupportedLookAndFeelexception e) {
e.printstackTrace()s
} catch (ClassnotFoundéxception e) {
e.printstackrrace();
} catch (Instantiationéxception e) {
e.printstackTrace();
} catch (IlegalAccesstxception e) {
e.printstackTrace();
>
‘The alternative Look and Feel (under Windows System) are
// Native systes Look and Feel
Unmanager.setLookand?eel(UrManager. getSystenLookandFeelclassNane());
1/ Cooss-platform Java Look and Feel (also called “Metal")
Uimanager.setLooedndreel("javax. swing. plaf.netal MetalLockndFeel");
|nps:iiww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m 2042‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
1/ windows Look and Feel
Uimanager.setLookdndFeel("con.sun.java.swing-plaf.windows.WindewsLookAndFeel");
1/ Cross-platform Ninbus Look and Feel (20K 1.6ut8)
Uimanager.setLootdndFeel("javax. swing. plaf.ninous.NimbusLockAndFesi") ;
11 Windows Classic Look and Feel
imanager. setLookandFeel "con. sun. Java-swing.plat windows WindowsClassicLookAndFeel");
1/ COE/MOtL# Look and Feel
imanager setLooksndFeel "cos. sun. java. swing. plat.motit.Mot¢LookAndFeel”);
You can use static method UIManager. getInstalledlookAncFee!s() to list all the installed LAF
Uimanager.LookAndFee1nfo{] lafs = UIManager.getInstalledLookAndFeels();
for (UiManager.LookAndFeelInto laf : Lats) ¢
systen.out printin(Ia#);
>
Javax. swing. UIManager$LookAndFeelTrfo[Metal javax.swing.plaf.etal.MetalLookAndreel}
Javax. swing, uimanager$LookandFeel info[Ninbus. javax.swing-plat.nimbus .NinbusLookAndf eel]
Javax. swing. UIManager$LookAndFeeltrfo[COE/Mot# com.sun. java. swing. plaf.motif.MotifLookAndFee)]
Javax. swing. UManager$LookandFeelnfo[Windows cos. sun. java. swing. plaf.windows.WindowsLookAnd eel]
Javax, swing, Uimanager$LookAndFeelinfo[Windows Classic con. sun. Java. swing. plaf windows. WingowsClassicLookAndFeel]
Via the Command Line Option “swing.defaultlaf”
For example,
11 set to Ninbus Lar
{java -Dswing.defaultlaf=javax. swing. plaf.ninbus.NinbusLockAndFeel MySwingapp
11 Set to Windows LaF
Java -Dswing. deFaultlaf=con. sun. java.swing.plaf windows WindowsLookAndFeel MySwingpp
Via the “swing. properties”
Create a “swing.properties’ fle (placed under “$3AVA_HONE/14b" directory) with a option “swing.default lar”
4 Swing Look and Feel
swing defavltlaf=Javax.swing-p1a¢.niabus .NinbustookAndF eel
2.2_ Nimbus Look and Feel (JDK 1.610)
Reference: Swing Tutorial’ "Nimbus Look and Feel” @ http://docs oracle.cornjavase/tutorial/uswing/lookandfeel/nimbus html
Nimbus is 9 polished cross-platform look and feel introduced in the JOK 1.6 Update 10, The JEC demo "SwingSes3" (under the JOK
demo) shows the Nimbus look and feel forthe various Swing 3Conponents. "Nimbus uses Java 2D vector graphics to draw the user
interface (UN, rather than static bitmaps, so the Ul can be crisply rendered at any resolution. Nimbus is highly customizable. You can
se the Nimbus look and feel asi, or you can skin (customize) the look with your ow brand.”
To enable Nimbus LAF:
1. Use uIManager. setLookandFee1():
wry
1/ Set to cross-platfore Nimbus Lock and Feel
UulManager. setLooktndFeel("Javax.swing.plaf.ninbus.MinbusLookAndFeel"); // 20% 1.7
} caten (Exception e) (
e.printstackInace();
?
1/ 08 more robust codes
wy ¢
1/ Check Af Minbus $s supported and get Sts elassnane
for (UIManages, LookkndFeelTafo lafinfo + UIManager.getTnstalledLookandFeels()) {
1 (°Minbus" .equals(1aFInfo.getNane())) {
‘nps:iwww3.ntu.edu sgfhomelehchualprogramminglavalida_GUL 2m! 2542‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
‘imanager -setLookandree} (Lafinfo.getClasshane())
break;
?
d
} eaten (Exception ) (
try (
1/1 Nimbus 4s not available, set to the defavit Java (retal) look and feel
Urmanager.setLookAndFeel(UIManager. getCrossPlatformLookAndFeelClassHane());
} catch (Exception et) {
el printstacktrace();
>
>
Take note that the Nevbus package in JDK 1.6u10 is “com. sun. java. swing. plaf.ninbus.NinbusLookAndFee1"; while in JDK
17, itis called "javax. swing. plaf.ninbus.NimbusLookAndFee]”
2. Use command-line option "swing.defaultiar”
Java -Dswing.defaultlafjavax.swing.plaf.nisus.Ninbustockandreel MySwingApe
3. Use a "swing. properties" fle (under the "$2AVA_HOME/ Lib")
4 Set to Ninbus Look and Feel (Systen-wide)
swing defavltlaf~Javax.swing.plaf.nimbus .NinbusLookkndF eel
‘A Nimbus component can have 4 cifferent sizes: large, regular, small and mini, You can choose the size via:
syButton.putclientProperty("2Component.sizeVariant", "mini");
11 default is “regular”, options are "large", “stall” and “nin”
You can change the color theme via
tmanager.put
vtmanager.put
tmanager.put
ininbusBase", new Color(...)); // Base color
iniabusBluesrey", new Color(.-.))5 // BlueGrey
control", new Calor(...))3 1 Control
1/ set to Ninbus LaF
for (LookAndFeelinfo info : UIManager.getInstalledLookandFeels() {
EF ('Niebus” equals(info.getnare())) (
UtManager. setLookAndFeel (Info. getClassName));
break
»
You can customize the look and feel, which is beyond the scope ofthis article.
3. More on Layout Manager
Reference: Swing Tutorials. -— “Laying = Out_— Components. —Within. «=a Container’
httpy//does oracle comyjavase/tutorial/uiswing/layout/index html
3.1. Key Points on Layout Manager
Layout in Production
Use NetBeans’ visual GroupLayout to layout the components in production; or GridBagLayout if you prefer to code yourself (why?)
The rest of LayoutManagers (such as FlowLayout, BorderLayout, GridLayout) are meant for prototyping.
The two components you need to worry about layout are Panel. and the content-pane of the top-level containers (such as 2Frane,
dApplet and IDialog).
= JPanel defaults to FlowLayout (with alignment of CENTER, hgap and vgap of S pixels): or you can set the layout of a 3Panel in its
constructor,
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m! 26142‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
= All contentspanes default to Bordertayout (with hgap and vgap of 0). In GorderLayout, the adé(acompanent) without
specifying the zone adds the component tothe CENTER. Second add) will overide the first add),
[Absolute Positioning without LayoutManager shall be avoided, as it does not adjust well on screens with different resolutions; or when
the window is resize,
Hints on sizes and alignments
You can provide hints on the minimum, preferred and maximum sizes of a component via setMinimuaSize(), setPreferredsize()
and setMaximunsize() methods. However, some layout managers ignore these requests, especially the maximum size. You can also
do these by extending a subclass and overriding the getXxxSize() call-back methods.
The setsize() method must be issued at the correct point, or else it will not work (as it was overridden by another implicit
setize()). (TODO: Check)
Similarly, you can provide hints on horizontal and vertical alignments (of the edges) among components via setALignnentX() and
setAligneent¥() methods. BoxLayout honors them but other layout managers may ignore these hints. You can also extend a
subclass and override the getALignnentX() and getAlignnentY() call-back methods.
TODO} setsize(), pack(), validate) and invalidate() for Container, revalidate() and repaint() for Component,
dotayout()
3.2 Methods validate() and doLayout()
If you change a property of a LayoutManager, such as hgap or vgap of GridLayout, you need to issue 2 doLayout() to force the
LayoutManager to re-layout the components using the new property
‘A container has only one LayoutManager. Nonetheless, you can change the LayoutManager via setLayout (newLayoutManager),
You need to follow with a validate() to ask the container to re-layout the components,
Code Example
‘This example creates 6 buttons, which are arranged in 3x2 and 2x3 GriéLayout alternately upon clicking any button
1 import javaawt.*;
2 import java.awt.event.*;
3 import javax.swing.*5
4
5 /** Changing the LayoutManager of the Container
6 between 3*2 GridLayout and 2*3 GridLayout */
7 @SuppressWarnings("serial")
@ public class SetLayoutTest extends JFrame {
9 private Int rows = 3;
10 private int cols = 2;
31 private Container
se Di
59}
eo }
‘Altermatively, you can also change the rows and columns of Gridlayout via setRows() and setColusns() methods, and
doLayout(). For example,
Goverride
public void actionPerformed(ActionEvent e) ¢
U1 Swap rows and cols
Ant tenp = rows;
rows = cols:
cols = temps
Geiatayout layout = (Gridtayout)
1
a7 Af (1 == nunbuttons - 1) {
48 buttons [é] = new 2Button(*Renove");
49 cp.add(buttonsti]) 5
50 buttons[s] -addtctionListener(Listener);
31 y
52 cp.validate()3 // needed after adding/renoving conponent
33 repaint(); // needed to cleanup dirty background
sa}
35
536 /** Inner class used as the ActionListener for the Buttons */
57 private class ButtonsListenen inplenents ActionListener {
se override
59 public void actionPerformed(ActionEvent e) {
6 // adjust the number of buttons
6 AF (e.getactionCoemand() .equals("Add")) {
62 sanunButtons;
6 p else ¢
6a Af (nurButtons >= 2) {
6 =-nunButtons;
68 ?
7 >
nps:iiwww3.ntu.edu sgfhomelehchualprogramminglavalida_ GUL 2m! 2042‘0sio12023, 13:17 GUI Programming Pan 2 Java Programming Tutorial
68 1/ Call helper nethod to create nunButtons buttons
69 ereateButtons();
70 y
nm}
n
TB /** The entry wain() method */
74 public static void main(String] args) {
1% 1/ Run GUI codes in the Event-Dispatching thread for thread safety
7 SwingUtilities. invokeLater(new Runnable) {
n public void run() {
8 new AddRemoveCorponentsTest(); // Let the constructor do the job
7% y
20 De
a}
2}
Most languages from written form left-to-right, but some otherwise. You can set the orientation on Component via
IV 3ava.ant..Conponent
Public vole setConponentordentation(Conzonentorientation 0)
11 ConponentOrientation.LEFT_TO_AIGHT or RIGHT_TO_LEFT.
Since JDK 14, layout managers, such as FlowLayout and BorderLayout, can layout components according to component-orientation|
‘of the container, Some new terms were intraduced, For example, in BorderLayout, instead of using EAST, WEST, NORKT, SOUTH (which
fare absolute), the term LINE_START, LINE_END, PAGE_START, PAGE_END were added which can adjust itself according to the
component orientation, LINE_START is the same as WEST, if the component orientation is LEFT_TO_RIGHT. On the other hand, itis
EAST, if the component orientation is RIGHT_TO_LEFT. Similarly, in FlowLayout's alignment, LEADING and TRAILING were added in
place of LEFT and RIGHT.
Code Example
1 import java.awt.*;
2 import java.awt-event.*;
3 import javax.swing.*;
4
5 /** BorderLayout bene */
6 @Suppresskarnings(“serial”)
7 public class GordertayoutTest extends JFrame {
3 public static final String TITLE = "BorderLayout Deno";
°
10 _// Private variables of GUI components
11 private Container ep; _// content-pane of this 3Frane
32 private 2Button btnNorth, btnSouth, BtnCenter, btnEast, btnwest;
13 private boolean leftToRight = true;
14
15 /** Constructor to setup the UI components */
16 public BorderLayoutTest() {
vv cp = this. getContentPane();
Py btnllorth = mew 38utton("PAGE_START [HIDE]");
re btnsouth = new 3Button( "PAGE_END [HIDE]");
20 btniest = new 3Button("LINE_ START [HIDE]");
a btnBast = new 3Button("LINE_END [HIDE]");
2 btncenter = new JButton("CENTER [SHOW ALL, CHANGE ORLENTATION]");
2a btncenter. setPreferredsize(new Dimension(388, 108)); // set size for CENTER
24
25 ActionListener Listener = new @uttonListener();
26 benNorth.addactionListener(Listener);
a7 bbtnsouth.addactionListener( Listener) ;
8 benast .addActLonListener(listener);
29 btnwest -addactionListener(listener);
Fr btncenter.addActionListener(listener);
hips: ww. ntu.odu sghhomelehchualprogramminglaval4a_GUL_2.hinl 30142‘0sio12023, 13:17 GUI Programming Pan 2 Java Programming Tutorial
a1
32 11 hdd a1 buttons to the content-pane
33 addputtons();
34
35 setDefaultCloseOperation(JFrane.EXIT_ON_CLOSE); // exit if close button clicked
36 setTitle(TITLE); // "this" JFrane sets title
a7 pack(); // "this" JFrame packs all its components
38 SetLocationRelativero(null); // center the application window
39 setVisible(true); 1 show it
0}
a
42 /** Helper method to add all buttons to the content-pane */
43 private void addButtons() {
44 ep.renoveAll();
45 cp.setConponentOrientation(leftToRight ?
46 ConponentOrientation.LEFT_TO_RIGHT : ConponentOrientation.RIGHT_TO_
a7 ep.add(btnNorth, BorderLayout.PAGE_START);
48 cp.add(btnsouth, Bordertayout.PAGE_eND);
49 ep.add(btniest, SorderLayout. LINE START);
50 cp.add(btnéast, BorderLayout .LINE_END);
st cp.add(btncenter, BorderLayout .CENTER);
52 cp.validate();
33}
34
5$ __/*¥ Inner class used as ActionListener for all buttons */
56 _private class ButtonListener inplenents ActionListener {
37 eoverride
38 public void actionPerformed(ActionEvent evt) {
59 3Button source = (2Button)evt.getsource();
60 (source == btnCenter) {
6 LeftToRight = LefeToRight; // toggle
6 adabuttons();
a } else (
6a ep.renove(source)
65, cp.validate();
6 >
o7 y
ee}
69
72 —_/** The entry wain() method */
71 public static vod main(String] args) {
n 11 Run GUI codes in the Event-Dispatching thread for thread safety
a SwingUtilities. invokeLater(new Ruanable() {
™ override
% public void run() {
7 new BordertayoutTest(); // Let the constructor do the job
7 }
7" De
7~ 3
Bo}
3.5. Absolute Positioning Without a Layout Manager
You could use absolute position instead of a layout manager (such as FlowLayout or
BorderLayout) by invoking method setLayout (null). You can then position you
components using the method setSounds(int xTopLeft, int yTopLeft, int
width, int height). For example
‘AosouePoining Dee
hips: ww. nu od sghhomelehchualprogramminglavalJ4a_GUL_2.hiel ae‘0si012023, 13:17 {GUI Programming Part2- Java Programming Tutor
0
a
2
3
Pr
is
a6
vv
18
Pry
20
a
2
23
23
26
7
28
29
30
3
2
33
35
36
a7
import java.awt.*;
import javax.swing.*;
/** Test Absolute Positioning */
public class CGAbsolutePositioning extends JFrane {
1° Constructor to setup the GUI components */
public CGdbsolutePositioning() (
Container cp = getcontentPane();
cp.setLayout(null); // disable layout manager - use absolute layout
dPanel pl = new 3Panel();
pl.setBounds(38, 30, 100, 100);
pi. setBackground(Color RED) ;
cp.add(p1) 5
pPanel p2 = new 3Panel();
p2.setsounds(158, 58, 120, 88);
2. setBackground(Colon. BLUE);
ep.add(p2) 5
setbefaul tCloseOperation( JFrame. EXIT_ON_CLOSE);
setTitle(“Absolute Positioning Deno");
setSize(40e, 200);
setvisible(true);
)
/** The entry ain method */
public static void main(string{] args) {
11 Run GUI codes in Event-Dispatcning thread for thread safety
SwingUtilities. invokeLater(new Runnable) {
override
public void run() (
new CGAbsolutePositioning(); // Let the constructor do the job
y
Di
4. More on Event-Handling
Both AWT and Swing applications uses the AWT event-handling classes (in package java.awt event). Swing added a few new event
hhandling classes (in package javax. swing. event), but they are not frequently used,
|AWT GUI Components (such as Button, TextField, and Window) can trigger an AWTEvent upon users activation,
Event Event Listener
User Action
Triggered interface
Click a Button, Button Actionfvent ActionListener
pen, iconity, close Frame, Windowevent _WindowListener
aFrane
Click a Component, MouseEvet __MouseListener
3Conponent
Change textsina TextField, TextEvent TextListener
aTextFielé
Type a key KeyEvent, KeyListener
Click/Select an item in a TtenEvent, ItenListener,
Choice, Icheckbox, Actionfvent ActionListener
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m!‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
RadioButton, IConbobox
The subclasses of ANTEvent are as follows:
Object
“ EventObject
AuTEvent
Component Event
ActionEvent | | AdjustmentEvent
Focustvent | |ContainerEvent
(rissevere) [fextzvent
PaintEvent | | WindowEvent
InputEvent
ese) es
[Pausaveevent
4.1 java.util. eventobject
All event objects extends java.util. EventObject, which takes the source object in this constructor, and provides a getSource()
method
11 Constructor
public Eventobject(object source)
11 wethos
public Onject getsource()
Take note that the constructor takes an Object; and getSource() returns an instance of type Object. You may need to downcast it
back to its original type
4.2 ActionEvent & ActionListener
‘An Actionévent is fred, when an action has been performed by the user. For examples, when the user clicks a button, chooses a
‘meng iter, presses enter key in a textfield. The associated ActionListener interface declares only one abstract method, as fellows
public interface ActionListener extends java.util. EventListener {
public void actionPerformed(actionevent evt); // called-back when an action has been performed
>
From the ActionEvent argument evt, you may use evt .getActionConsand() to get a String related to this event, for example, the
bbutton's label, the String entered into the textfield, This is particularly useful if the same ActionEvent handler is used to handle
‘multiple source objects (eg, buttons or textfield), fr identifying the source object that triggers this ActLonEvent.
4.3. Swing’s Action
Read Swing Tutorials "How to Use Actions”
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m! a4,‘0sio12023, 13:17 {GUI Programming Part2- Java Programming Tutor
[A javas.swing.Action is a Actiontvent listener, If two or more components (e.g, a menu item and a button) perform the same
function in response to an Action vent, you can use an Action object to specify both the state and functionality of the components
(whereas actionPerforned() defines only the function). For example, you can specify the states such a5 the text, icon, shortcut key,
tool-tip text forall the source components,
You can attach an Action abject to a component via aConponent..setAction(anaction) method:
1. The component’ state (e.g, text, icon) is updated to match the state ofthe Action.
2, The component adds the Action object as an Actiontvent listener.
3. Ifthe state ofthe Action changes, the component’ state is updated to match the Action,
To create an Action object. you extend AbstractAction to provide the state and implement the actionPerformed() method to
response to the Action vent.
Example
In this example, a menu-item and a button share the
same Action. The Action object specifies the states
(text tookp’s text, and a mnemonic alt short-cut key)
and override the actionPerformed(). Take note that
the label on the buttons are updated to match the
Acton’ names.
1 Amport javax.swing.
2 inport java.awt.*;
3 inport java-awt event.
alee
5 + Test Actions which are ActionListeners that can be applied to more than one sources.
6
7
4
9
* An action can specify the state and functionality of an ActionListener.
”
@Suppressiarnings ("serial")
public class Testaction extends IFrame {
30 private ITextField tfcount;
11 private int count;
2
13 _/** constructor to setup the GUI */
14 public TestAction() {
15 JI Create the Actions shared by the button and menu-iten
16 Action countupaction = new Countupaction("Count Up",
v “To count up", new Integer(KeyEvent.VK_U));
Py Action countDownketion = new CountDownAction("Count Down"
19 "To count down", new Integer(KeyEvent.VK_b));
20 Action resetaction = new ResetAction("Reset”,
2 "To reset to zero”, new Integer(Keyevent .VK_R)
22
23 Container cp = getcontentPane();
24 ep.setLayout(new FlowLayout());
25
26 UI Create buttons
27 p.add(new ILabe("Counter: "));
28 téCouNt = new ITextField("@", 8);
29 ‘tFCount .setHorizontalAlignnent (JTextField. RIGHT) ;
30 ep.add(tfCount) ;
31 3Button btncountup = new 2Button();
32 €p.add(btncountup) 5
33 3Button btncountDown = new ISutton()s
34 €p.add(btncount Dawn);
35 Button benReset = new JButton();
36
95
96 override
7 public void actionPerformed(ActionEvent e) (
98 =-count}
99 ‘tfCount -setText(count + "");
200 ?
x}
ae
hips: Www. ntu.od sghhomeiehchualprogramminglavalJ4a_GUL_2.hiel 3642‘0si012023, 13:17 {GUI Programming Part2- Java Programming Tutor
303 public class ResetAction extends abstractaction {
104 1° Constructor */
305 public ResetAction(String name, String shortDesc, Integer mnenonic) {
306 supername);
107 putValue(SHORT_DESCRIPTION, shortdesc);
108 putValue(MNEVONTC KEY, mnemonic);
109 y
ne
an foverride
uz public void actionPerformed(ActionEvent e) {
3 count = @;
us tfcount.-setText(count +");
us »
us)
7
418 /** The entry main() method */
119 public static void main(Stringl] ares) (
ne 1] Run GUE codes in the Event-Dispatching thread for thread safety
aa ‘Javax. swing. Suingutilities. invokeLater(new Runnable() (
122 public void run() ¢
33 new TestAction(); // Let the constructor does the job
126 y
225 Ds
ws )
ny
4.4 WindowEvent & WindowListener/WindowAdapter
Interface WindowListener is used for handling WindowEvent triggered via the three special buttons (minimize, maximize/restore
down, and close) on the top-right corer of the window or other means. There are 7 abstract methods declared in the interface, as
follows:
public interface KindowListener extends java.util. EventListener {
public void windowClosing(WindowEvent evt);
// called-back when the user attenpt to close ¢
public void windowActivated(Windowévent evt);
1/ called-back when this window is set to the a
public void windoweactivated(Windowtvent evt);
71/ called-back when this window 45 no longer the active window
public void windowopened(Windowevent evt);
11 eatleé-back when this window is First made
public void windowClosed(hindowevent evt);
1] eatleé-back when the window has been closed
public void windowlconiFied(windoxévent evt);
{i ealleé-back when this window is minimized
public void windoweiconified(WindowEvent evt);
1/ called-back when this window is change fron mininize to noreal state
1s window, most commonly-used handler
>
‘The most commonly-used method is WindowClosing(), which is called when the user attempts to close this window via the "window
lose” button of “ile-ext” menuitem,
11 Sanple handler for windowClosing()
override
Public void WindonClosing(Windowevent evt) ¢
U1 Ask user to confirm
17 perform clean up operations
System.exit(@);// Teominate the progras
>
Windowadapter
|nps:iwwww3.ntu edu sgfhomelehchualprogramminglavalida_ GUL 2m! 642‘0sio12023, 13:17 GUI Programming Pan 2 Java Programming Tutorial
[A windostvent listener must implement the WindowListener interface and provides implementation to ALL the 7 abstract methods
declared, An empty-body implementation is required even if you are not using that particular handler, To improve productivity, an
‘adapter cass called WindowAdapter is provided, which implements WindowListener interface and provides default implementation to
all the 7 abstract methods. You can then derive a subclass from WindowAdapter and override only methods of interest and leave the
rest to their default implementation,
This example shows how to extend a WindowAdapter class, using an anonymous inner class, to handle a window-closing event
public class UiAppLicat:
public GULApplication()
‘this addWindonListener(new WindowAdapter() {
Override
Public void windowClosing(Windowevent evt) {
system.exit(2);
y
ys
JFrame's setDefaultCloseoperation()
In Swing's 3Frane, a special method called setDefaultCloseOperation() is provided to handle clicking of the “window-close"
button. For example, to exit the program upon clicking the close-window button, you can use the following instead of
KindowListener or WindowAdapter.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exit progran upon clicking window-close button
Similarly, most of the event lstener interface has its equivalent adapter, e.g, Mousedapter for MouseListener interface, KeyAdapter
for Keylistener interface, MouseMotionAcapter for MouseMotionlistener interface, There is no ActionAdapter for
ActionListener, because there is only one abstract method insde the ActionListener interface, with no need for an adapter.
'A word of caution: If you implement the WindowListener yourself and misspell a method name says windowClosing() to
kinowClosing(), the compiler will signal an error to notify you that windowClosing() method was not implemented. However, if you
extend from WindowAdapter class and misspell a method name, the compiler treats the misspell method as @ new method in the
subclass, and uses the default implementation provided by WindowAdapter for handling that event. This small typo error took me a
few agonizing hours to debug, This prablem is resolved via the annotation @Overrie introduced in JDK 1.5, which tells the compiler
to issue an error if the ann:
ted method does not override its superclass,
4.5 KeyEvent & KeyListener/KeyAdapter
The KeyListenen interface defines three abstract methods:
void keyTyped(KeyEvent evt)
1/ Called-back when 2 key has been typed (pressed followed by released)
void keyPressed(KeyEvert evt)
11 Called-back when a key has been pressed
void keyReleased(KeyEvent evt)
1/ Caliback when a key has been released
There are two kinds of key events:
‘The typing of a valid character, eg, ‘3°, ‘A’. Thsis called a key-fyped event.
2, The pressing or releasing of a key, €.9, up-arrow, enter, 'a", shirft+'a", Ths isa key-pressed or key-released event
Use keyTyped() to process key-typed event, which produces a valid Unicode character. You can use evt .getKeyChar() to retrieve
the char typed. getKeychar() can differentiate between 'a" and °A" (pressed shift+"a").
You can use keyPressed() and keyReleased() for all the keys, character key or others (such as up-arrow and enter). You can use
evt.getkeyCode() to retrieve the int Virtual Key (VK) code, e.g, KeyEvent .VK_UP, KeyEvent..VK_ENTER, KeyEvent.VK_A. You can
also use evt. getKkeyChar() to retrieve the unicode character, ifthe event produced a valid Unicode character.
hips: ww. nu od sghhomelehchualprogramminglavalJ4a_GUL_2.hiel area‘0sio12023, 13:17 GUI Programming Pan 2 Java Programming Tutorial
getKkeyCode() vs. getkeyChar()
« Ifyou press "a" key, getKeyChar() returns ‘a’ and getKeyCode() returns VK_A,
+ you press shifts a", two key-pressed events and one key-typed event triggered, getKeyChar() returns ‘A’ and getKeyCode()
returns VK_SH
inthe first key-pressed event and VK_A in the second event. The first key-pressed event is often ignored by the
program
Notice that Virtual Key codes, key-char are used, instead of actual key code, to ensure platform and keyboard-layout independent.
For Example,
1 import java-awt.*;
2 import java.awt-event.*;
3. import Javax.swing.*;
4
5 /** Test KeyListener */
6 public class KeyListenerTest extends JFrane inplenents KeyListener {
7 /** Constructor to setup the GUI */
3 public KeyListenerTest() {
° Container cp = getcontentPane();
10 cp.addkeyListener(this) ;
ua 11 Need to enables receiving of key inputs for this GUI component,
2 cp.setFocusable(true) ;
B 11 "May" need to request keyboard focus on this component
14 ep.requestFocus();
16 setDefaul tcloseOperat ion(3Frase.EXIT_ON_CLOSE);
v setTitle("Testing Key Listener”);
Pry setSize(30@, 200);
ce setvisible(true);
2}
a
22 override
23 public void keyTyped(keyevent ) (
24 char keyChar = e.getkeychar();
25 systen.out.printIn("keyTyped: Key char is " + keyChar)s
2%}
a7
28 @override
29 public void keyPressed(keytvent e) {
30 int keyCode = e.getkeyCode();
a1 char keyChar = e.getKeyChar();
32 Systen.out.printin("keyPressed: VK Code is " + keyCode +", Key char is " + keyChar);
3}
34
35 @override
36 public void keyReleased(KeyEvent e) {} // Ignored
”
38 /** The entry main method */
39 public static void main(string[] args) {
40 11 Run GUI codes on the Event-Dispatching thread for thread safety */
an SwingUtiLities. invokeLater(new Runnable) {
2 override
a public void run() (
4a new KeyListenerTest(); // Let the constructor do the job
4s >
46 »
a7}
a}
Try pressing “a, “A (shifte'2), enter, up-arrow, ete, and observe the key-char and VK-cade produced by keyTyped() and
keyPressed()
hips: ww. nu od sghhomelehchualprogramminglavalJ4a_GUL_2.hiel a2