1 1. About Swing 2. The Applet Framework 3. A first Applet 4. Swing Applications 5. The Swing Event model 6. Containment hierarchies 7. Swing Taxonomy
Jan 17, 2016
1
1. About Swing2. The Applet Framework3. A first Applet4. Swing Applications5. The Swing Event model6. Containment hierarchies7. Swing Taxonomy
2
History
Goal : Library to support (G)UIs
Java 1.0 AWT • looks the same (“mediocre”) on all platforms• restrictive (e.g. only 4 fonts available)• not OO ! Java 1.1 AWT • OO event model • JavaBeans Component model
First shot : Abstract Window Toolkit (AWT)
3
History
• nickname : “Swing”• adds :
• plugable look-and-feel• many new components• “light-weight components”
no native code (-> better appearance !)• support for automatic code generation (GUI-builders)
Second (3 ?) shot : Java Foundation Classes (JFC)
4
Philosophy : MVC
Model-View-Control architecture
View Controller
Data ModelClass contains• data• computations
Class presentedto the user
Controls :• data model (change, compute, …)• how data is presented to user
5
Applet ?
= Small application run in browser environment
- security restrictions (e.g. no hard disk access)- slow to display (due to download)+ no installation (automatic latest code !)+ no catastrophe due to malicious code
6
Applet - Browser interaction
Browser interprets HTML-page
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><html><head><title>Algoritmisch Denken en Programmeren</title><meta name="GENERATOR" content="Microsoft FrontPage 3.0"></head>
<body>
<h1 align="center">Algoritmisch Denken en Programmeren </h1><h2 align="center">academiejaar 2000 - 2001</h2>
<dir> <li>Lesgevers : Bart Dhoedt en Mario Pickavet</li> <li><a href="#Berichten aan studenten">Berichten aan studenten</a></li></body></html>
7
Applet - Browser interaction
Special applet-tag :
parameters codebase : location of Applet class filecode : name of Applet class fileheight : height of Applet area (in pixels)width : width of Applet area (in pixels)
<applet codebase="http://www.atlantis.rug.ac.be/inforasi/applets" code=AnApplet width=100 height=100> </applet>
• browser allocates (width x height) area for Applet• starts execution of Applet
8
Testing Applets ...
// <applet code=AnApplet width=100 height=100> </applet>
Appletviewer
• searches for <applet>-tag in text file• executes the Applet
Trick
Add to your *.java file :
9
Applet Class
4 methods• init() : called once when Applet is created (performs layout)• stop() : called each time Applet goes out of window• start() : called each time Applet gets back into window• destroy() : called once when page is removed from browser
window
10
Applet class
JApplet
+init()+stop()+start()+destroy()
M yJApplet
+init()+stop()+start()+destroy()
Brow serVM
controls
How to code a JApplet ?
• import appropriate packagesimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;
• make a public class, extending JApplet• override at least init()
11
Coding Applets// <applet code=MyApplet width=100 height=100> </applet>import javax.swing.*;import javax.swing.event.*;
public class MyApplet extends JApplet {// class data// class operationspublic void init() {
}} // end of class MyApplet
12
Hello World !
// Source File : FirstApplet.java// <applet code=FirstApplet width=100 height=100> </applet>
import javax.swing.*;import javax.swing.event.*;
public class FirstApplet extends JApplet {public void init() {
JLabel text = new JLabel("Our first Applet !");getContentPane().add(text);
}} // End of class FirstApplet
Test with appletviewer :
C:\> appletviewer FirstApplet.java
13
Hello World !
Test with browser :
(1) construct HTML-file<html><head> <title> Illustration of an Applet running in a Browser </title></head><body>This is a first Applet :<hr><applet code=FirstApplet width=100 height=100> </applet><hr></body></html>
14
Hello World !(2) RUN HTML-converter
<html><head> <title> Illustration of an Applet running in a Browser </title></head><body>This is a first Applet :<hr><!--"CONVERTED_APPLET"--><!-- CONVERTER VERSION 1.3 --><OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93”WIDTH = 100 HEIGHT = 100 codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0"><PARAM NAME = CODE VALUE = FirstApplet ><PARAM NAME="type" VALUE="application/x-java-applet;version=1.3"><PARAM NAME="scriptable" VALUE="false"><COMMENT><EMBED type="application/x-java-applet;version=1.3" CODE = FirstApplet WIDTH = 100 HEIGHT = 100 scriptable=false pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html"><NOEMBED></COMMENT></NOEMBED></EMBED></OBJECT><!--<APPLET CODE = FirstApplet WIDTH = 100 HEIGHT = 100></APPLET>--><!--"END_CONVERTED_APPLET"--><hr></body></html>
15
Hello World !
(3) Open browser and select generated html-file
16
Applet Framework// Source File : AppletFramework.java// <applet code=AppletFramework width=500 height=100> </applet>import javax.swing.*;import javax.swing.event.*;public class AppletFramework extends JApplet {
private String labelText="<INIT>";JLabel text = new JLabel(labelText+" ");public void init() { getContentPane().add(text);
System.out.println("<INIT>");}public void stop() { labelText+="<STOP>";
text.setText(labelText); System.out.println("<STOP>");
}public void start() { labelText+="<START>";
text.setText(labelText); System.out.println("<START>");
}public void destroy() { labelText+="<DESTROY>";
text.setText(labelText); System.out.println("<DESTROY>");
}} // End of class AppletFramework
17
Applications
• same possibilities as text applications• + graphical components• has main()-method !
How to code Applications ?
• code a class extending JFrame• include a public constructor, performing initialisation (cf. JApplet’s init() method !)• create an object of this class
18
Applications
import javax.swing.*;import javax.swing.event.*;class MyApplication extends JFrame {
public MyApplication(String title) {super(title); // sets frame title// add operations here
}} // End of class MyApplication
public class MyApplicationTest { public static void main(String[] args) {
MyApplication app=new MyApplication(”<Add title of application here.>");app.setSize(200,200); // sets width and height of frameapp.setVisible(true); // makes the frame visibleapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // since JDK1.3 !
}} // End of class FirstApplicationTest
19
Applications
JFram e
+JFram e(title : S tring)+setV isible(b : boolean)+setS ize(width : int, height : int)+setDefaultC loseOperation(operation : int)
+EXIT_ON_CLOSE : int
M yApplication
+MyApplication(title : S tring)
M yApplicationTest
+m ain(args : S tring[])
20
A First Application
// Source File : FirstApplicationTest.javaimport javax.swing.*;import javax.swing.event.*;class FirstApplication extends JFrame {
public FirstApplication(String title) {super(title); // sets frame titlegetContentPane().add(new JLabel("Our first application !"));
}} // End of class FirstApplicationpublic class FirstApplicationTest { public static void main(String[] args) {
FirstApplication app=new FirstApplication("Title : Graphical Application.");app.setSize(200,200);app.setVisible(true);app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // since JDK1.3 !
}} // End of class FirstApplicationTest
21
Concept
Swing componentclass
Application class
Interface class• presents component to user• intercepts user interaction
Instantiates Swing components
Code to act upon user input ? ListenerObject
22
Concept
Swing componentclassApplication class
ListenerObject
Interface class• presents component to user• intercepts user interaction
• Instantiates • Swing components• Listener objects
Contains handling code
• makes connection between listener and Swing object
Calls back handling codeof all registered listeners
23
Concept
JTextField
Application class
Listener Object
...
JTextField f = new JTextField(20);
Listen a = new Listen();
f.addActionListener(a);
public void actionPerformed(ActionEvent e) {// …
}
EN
TER
PR
ES
SE
D
ActionEvent object
24
Concept
Listener object • Must implement interface agreed with Swing class generating event• JTextField, JButton requires ActionListener
class JTextField {Vector listen=new Vector();public void addActionListener(ActionListener a) {
listen.addElement(a);}private void fireEvents {
ActionEvent e = new ActionEvent();for(int i=0;i<listen.size();i++)
((ActionListener)listen.elementAt(i)).actionPerformed(e);}
}
Listener class usually implemented as inner class !
25
Listener optionsOption 1 : Listener class named inner class
class ListenText extends JFrame {JLabel a = new JLabel("Please input text : ");JTextField f = new JTextField(25);ListenText(String title) {
super(title);Listen l = new Listen();Container cp=getContentPane();cp.setLayout(new GridLayout(1,2));cp.add(a);cp.add(f);f.addActionListener(l);
}private class Listen implements ActionListener {
public void actionPerformed(ActionEvent e) {System.out.println("ENTER PRESSED !");
}}
}
ListenerObject
Registration
ListenerClass
26
Listener optionsOption 2 : Listener class named inner class
anonymous listener object
class ListenText extends JFrame {JLabel a = new JLabel("Please input text : ");JTextField f = new JTextField(25);ListenText(String title) {
super(title);Container cp=getContentPane();cp.setLayout(new GridLayout(1,2));cp.add(a);cp.add(f);f.addActionListener(new Listen() );
}private class Listen implements ActionListener {
public void actionPerformed(ActionEvent e) {System.out.println("ENTER PRESSED !");
}}
}
ListenerClass
ListenerObject
Registration
27
Listener optionsOption 3 : Listener class anonymous inner class
anonymous listener object
class ListenText extends JFrame {JLabel a = new JLabel("Please input text : ");JTextField f = new JTextField(25);ListenText(String title) {
super(title);Container cp=getContentPane();cp.setLayout(new GridLayout(1,2));cp.add(a);cp.add(f);f.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { System.out.println("ENTER PRESSED :"+f.getText());}
} );}
}
ListenerObject
ListenerClass
Registration
28
Listener optionsOption 4 : Listener class anonymous inner class
named listener object
class ListenText extends JFrame {JLabel a = new JLabel("Please input text : ");JTextField f = new JTextField(25);ListenText(String title) {
super(title);Container cp=getContentPane();cp.setLayout(new GridLayout(1,2));cp.add(a);cp.add(f);ActionListener l=new ActionListener() {
public void actionPerformed(ActionEvent e) { System.out.println("ENTER PRESSED :"+f.getText());}
};f.addActionListener(l);
}}
ListenerObject
ListenerClass
Registration
29
Listener options
Named Anonymous
Named
Anonymous
• >1 objects of listener class• listener to > 1 Swing object
• >1 objects of listener class • listener to 1 Swing object
• 1 object of listener class• listener to >1 Swing object
• 1 object of listener class• listener to 1 Swing object
Lis
ten
er O
bje
ct
Listener Class
30
Listeners
Construct a Swing application :• label shows text : “Put lower case text here : “• text field (width 30) to input text• when “ENTER” is pressed, text in text field is put in upper case
Use JTextField methods :• public void setText(String)• public String getText()
31
Listenersclass UpperCase extends JFrame {
// UI-components UpperCase(String title) {
super(title);Container cp=getContentPane();cp.setLayout(new GridLayout(1,2));cp.add(a);cp.add(f);// ...
}}public class UpperCaseTest { public static void main(String[] args) { UpperCase app=new UpperCase("Change to Upper"); app.setSize(500,200); app.setVisible(true); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
32
Many listeners
Application object
Swing object
USE
RA
CTI
ON
Event Object
Listener object
Listener object
callback
callback
33
Many listenersclass ManyListen extends JFrame {
JLabel a = new JLabel("Type your text : ");JTextField f = new JTextField(30);ManyListen(String title) {
super(title);Container cp=getContentPane();cp.setLayout(new GridLayout(1,2));cp.add(a); cp.add(f);f.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {System.out.println("I'm listening ... ");
}});f.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {System.out.println("Me too ... ");
}});
}}
Callback order ???
34
Many listeners
Construct a Swing application :• label shows text : “Input text : “• text field (width 30) to input text• register array of listener
Listener object :• has a number• appends number to text in text field
35
Many listeners
class ArrayListen extends JFrame {JLabel a = new JLabel("Type your text : ");JTextField f = new JTextField(30);ArrayListen(String title) {
super(title);int listenSize = 4;Container cp=getContentPane();cp.setLayout(new GridLayout(1,2));a.setFont(font);f.setFont(font);cp.add(a);cp.add(f);// ...
}// ...
}
36
ONE listener
Application object
Swing object 1
USE
RA
CTI
ON
Listener object Swing object 2
Swing object 3
Event Object 1
Event Object 2
Event Object 3
callback
USE
RA
CTI
ON
callback
callback
USE
RA
CTI
ON
37
ONE listener
Listener object• is called back by many objects• action should depend on originator
Use of Event-object
getSource() yields REFERENCE to event firing object
38
ONE listenerclass OneListen extends JFrame {
JLabel first = new JLabel("Type your first name : ");JLabel last = new JLabel("Type your last name : ");JTextField firstName = new JTextField(30);JTextField lastName = new JTextField(30);OneListen(String title) {
super(title);Container cp=getContentPane();cp.setLayout(new GridLayout(2,2));cp.add(first);cp.add(firstName);cp.add(last);cp.add(lastName);ActionListener l=new ActionListener() { public void actionPerformed(ActionEvent e) { JTextField t=(JTextField)e.getSource(); if(t==firstName) { System.out.println("Input in first name.");
t.setText((t.getText()).toLowerCase()); } else { System.out.println("Input in last name.");
t.setText((t.getText()).toUpperCase()); } }};firstName.addActionListener(l); lastName.addActionListener(l);
}} Try to avoid type-checking code !
39
ONE listener
Construct a Swing application :• array of text fields shown in a column• concatenation of text shown in label 1• sequence of text fields “entered” shown in label 2
40
ONE listener
class ListenToArray extends JFrame {JLabel label1 = new JLabel("");JLabel label2 = new JLabel("");// ...ListenToArray(String title) {
super(title);int size=10;Container cp=getContentPane();// layout ???
// ...}
41
Dynamic event binding
Listener objects can be• registered• deregistered
during program execution
addActionListener(…)
removeActionListener(…)
Example
• two listener objects “red” and “green”• only one listener active at given time• turns text in text field in color defined• switches to other colour
42
Dynamic event bindingclass RedGreen extends JFrame {
JLabel label = new JLabel("Type your text here : ");JTextField text = new JTextField(30);ActionListener red,green;RedGreen(String title) {
super(title);Container cp=getContentPane();cp.setLayout(new GridLayout(1,2));text.setForeground(Color.green);cp.add(label);cp.add(text);red=new ActionListener() {public void actionPerformed(ActionEvent e) {
text.setForeground(Color.red);text.addActionListener(green);text.removeActionListener(red);
}};green=new ActionListener() {public void actionPerformed(ActionEvent e) {
text.setForeground(Color.green);text.addActionListener(red);text.removeActionListener(green);
}};text.addActionListener(red);
}}
43
In general ...
• Swing Components can fire Events
• Registered listener objects are called
• Listener objects implement agreed interface
XxxEvent
addXxxListenerremoveXxxListener
XxxListener
44
In general ...
XxxEvent
addXxxListener
XxxListener
Component JButton JCheckBox JFrame
ActionEvent ItemEvent WindowEvent
addActionListener addItemListener addWindowListener
ActionListener ItemListener WindowListener
45
Example : JFrame
Listener Object must implement WindowListener interface
• public void windowOpened(WindowEvent e)• public void windowClosing(WindowEvent e)• public void windowClosed(WindowEvent e)• public void windowActivated(WindowEvent e)• public void windowDeactivated(WindowEvent e)• public void windowIconified(WindowEvent e)• public void windowDeiconified(WindowEvent e)
46
Example : JFrameclass JFrameEvent extends JFrame {
JFrameEvent(String title) {super(title);}}public class JFrameEventTest { static JFrameEvent app=new JFrameEvent("Event Testing ..."); public static void main(String[] args) { app.setSize(200,100); app.setVisible(true); app.addWindowListener(new WindowListener() { public void windowOpened(WindowEvent e) {System.out.println("windowOpened");} public void windowClosing(WindowEvent e) {
System.out.println("windowClosing ...");app.dispose();}
public void windowClosed(WindowEvent e) {System.out.println("windowClosed ...");System.exit(0);}
public void windowActivated(WindowEvent e) {System.out.println("windowActivated");} public void windowDeactivated(WindowEvent e) {System.out.println("windowDeact.");} public void windowIconified(WindowEvent e) {System.out.println("windowIconified");} public void windowDeiconified(WindowEvent e) {System.out.println("windowDeicon.");} }); }}
47
Adapter ClassesMotivation• some interfaces contain a lot of methods• in lot of situations : only a few are useful• other methods must be implemented• -> a lot of methods are dummy methods
Java trick • all interfaces with more than 1 method : adapter class with empty methods• inherit from adapter class, and only define methods you need
48
Adapter ClassesExample : WindowListener
WindowListener
+windowO pened(e : W indowEvent) : vo id+windowC losing(e : W indowEvent) : vo id+windowC losed(e : W indowEvent) : vo id+windowActivated(e : W indowEvent) : vo id+windowDeactivated(e : W indowEvent) : vo id+windowIconified(e : W indowEvent) : vo id+windowDeiconified(e : W indowEvent) : vo id
MyWindow Listener
+windowO pened(e : W indowEvent) : vo id+windowC losing(e : W indowEvent) : vo id+windowC losed(e : W indowEvent) : vo id+windowActivated(e : W indowEvent) : vo id+windowDeactivated(e : W indowEvent) : vo id+windowIconified(e : W indowEvent) : vo id+windowDeiconified(e : W indowEvent) : vo id
Implementation without adapter class
public void windowOpened(WindowEvent e) { }…public void windowClosing(WindowEvent e) {
// things to do when window closes}…public void windowDeiconified(WindowEvent e) { }
49
Adapter ClassesExample : WindowListenerWindowListener
+windowO pened(e : W indowEvent) : void+windowClosing(e : W indowEvent) : void+windowClosed(e : W indowEvent) : void+windowActivated(e : W indowEvent) : vo id+windowDeactivated(e : W indowEvent) : vo id+windowIconified(e : W indowEvent) : vo id+windowDeiconified(e : W indowEvent) : void
Window Adapter
+windowO pened(e : W indowEvent) : void+windowClosing(e : W indowEvent) : void+windowClosed(e : W indowEvent) : void+windowActivated(e : W indowEvent) : vo id+windowDeactivated(e : W indowEvent) : vo id+windowIconified(e : W indowEvent) : vo id+windowDeiconified(e : W indowEvent) : void
MyWindow Listener
+windowClosing(e : W indowEvent) : void
Implementation withadapter class
public void windowOpened(WindowEvent e) { }…public void windowClosing(WindowEvent e) {
// things to do when window closes}…public void windowDeiconified(WindowEvent e) { }
public void windowClosing(WindowEvent e) {// things to do when window closes
}
50
Adapter ClassesExample : WindowListener
class WindowAdapterTest extends JFrame {WindowAdapterTest(String title) {
super(title);}
}public class AdapterTest { static WindowAdapterTest app=new WindowAdapterTest("Adapter Testing ..."); public static void main(String[] args) { app.setSize(200,100); app.setVisible(true);
app.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {
System.out.println("We're leaving the application !!!");app.dispose();System.exit(0);
} }); }}
51
Concept3 types of components
Top-level containers
Intermediary containers
Atomic components
• provide space for other Swing components• provide services for : layout and event handling• composed of menu bar and content pane (+ …)• examples : JFrame, JApplet, JDialog
• provide space for other Swing components• provide services for layout• example : JPanel
• can not hold other components• visible for user interaction (input/output)
52
Top-level containers
Menu bar
Content Pane
Title bar
class Chooser extends JFrame {Chooser(String title) {
super(title);JMenuBar menuBar=new JMenuBar();JMenu[] menus = {new JMenu("File"),new JMenu("Edit")
,new JMenu("Search"),new JMenu("Help")};for(int i=0;i<menus.length;i++) menuBar.add(menus[i]);setJMenuBar(menuBar);
}} Not added to the content Pane
53
Containers
• can hold other componentscreating a “containment” hierarchy
• components held controlled by• add(…)• remove(…)
• layout controlled by own layout manager• setLayout(LayoutManager l);• doLayout(); (force layouting)
54
Containers
Construct a Swing application (without event handlers),showing following layout :
JTextArea object
55
Containers
Containment hierarchyJFrame
Content Pane
JPanel light
JPanel buttons
JTextArea a JButtongreen
JButtonorange
JButtonred
56
Containers
class Traffic extends JFrame {JPanel light;JTextArea show = new JTextArea(“ \n\n\n”);;Traffic(String title) {
super(title);Container cp=getContentPane();// ...
}}
JFrame
Content Pane
JPanel light
JPanel buttons
JTextArea a JButtongreen
JButtonorange
JButtonred
57
Forcing layoutexample
class ForceLayout extends JFrame {Vector buttons = new Vector();Container cp;ForceLayout(String title) {
super(title);cp=getContentPane();cp.setLayout(new FlowLayout());JButton add = new JButton("Add a button");cp.add(add);add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {JButton b=new JButton("Button "+buttons.size());buttons.addElement(b);cp.add(b);
cp.doLayout();}
});}
}
58
Forcing Layout
Extend the previous example :• add a remove button• organize all buttons in 2 columns
59
Abstract Window Toolkit
The awt-package
java.aw t
Component
applet
Applet
Panel
Container
Window
Frame
Button
CheckBox
TextField
AWTEvent
event
Ato
mic
co
mp
on
en
ts
“containing” components
60
Events
The awt.event-package
java.aw t.event
AWTEvent
ActionEvent
Window Event
EventListener
ActionListener
WindowListener
61
Awt - Swing connection
java.aw t.Component
java.aw t.Container
javax.sw ing.JComponent
• hints for layouting (object size)• external representation of component (paint)• handling events associated with component
• add/remove components• perform layout (setLayout, doLayout)• decide when to (re)paint component
• parent class of all J******* classes except top-level containers• services to child classes :
• tooltips, borders, pluggable look&fee, layout support, ...
62
Swing java.aw t.Component
applet
Applet
java.aw t.Panel
java.aw t.Container
java.aw t.Window
java.aw t.Frame
javax.sw ing.JComponent
javax.sw ing.JWindow
javax.sw ing.JFrame
javax.sw ing.JApplet
javax.sw ing.JPanel
java.aw t.Dialog
javax.sw ing.JDialog
Atomicawt-components
Top-levelSwing containers
All otherSwing components