Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 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 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 4 Philosophy : MVC Model-View-Control architecture View ControllerData Model Class contains data computations Class presented to the user Controls : data model (change, compute, …) how data is presented to user

5 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 6 Applet - Browser interaction Browser interprets HTML-page Algoritmisch Denken en Programmeren Algoritmisch Denken en Programmeren academiejaar 2000 - 2001 Lesgevers : Bart Dhoedt en Mario Pickavet Berichten aan studenten

7 7 Applet - Browser interaction Special applet-tag : parameters codebase : location of Applet class file code : name of Applet class file height : height of Applet area (in pixels) width : width of Applet area (in pixels) <applet codebase="http://www.atlantis.rug.ac.be/inforasi/applets"http://www.atlantis.rug.ac.be/inforasi/applets code=AnApplet width=100 height=100> browser allocates (width x height) area for Applet starts execution of Applet

8 8 Testing Applets... // Appletviewer searches for -tag in text file executes the Applet Trick Add to your *.java file :

9 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 10 Applet class How to code a JApplet ? import appropriate packages import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; make a public class, extending JApplet override at least init()

11 11 Coding Applets // import javax.swing.*; import javax.swing.event.*; public class MyApplet extends JApplet { // class data // class operations public void init() { } } // end of class MyApplet

12 12 Hello World ! // Source File : FirstApplet.java // 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 13 Hello World ! Test with browser : (1) construct HTML-file Illustration of an Applet running in a Browser This is a first Applet :

14 14 Hello World ! (2) RUN HTML-converter Illustration of an Applet running in a Browser This is a first Applet : <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"> <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"> -->

15 15 Hello World ! (3) Open browser and select generated html-file

16 16 Applet Framework // Source File : AppletFramework.java // import javax.swing.*; import javax.swing.event.*; public class AppletFramework extends JApplet { private String labelText=" "; JLabel text = new JLabel(labelText+" "); public void init() { getContentPane().add(text); System.out.println(" "); } public void stop() { labelText+=" "; text.setText(labelText); System.out.println(" "); } public void start() { labelText+=" "; text.setText(labelText); System.out.println(" "); } public void destroy() { labelText+=" "; text.setText(labelText); System.out.println(" "); } } // End of class AppletFramework

17 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 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(” "); app.setSize(200,200);// sets width and height of frame app.setVisible(true); // makes the frame visible app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // since JDK1.3 ! } } // End of class FirstApplicationTest

19 19 Applications

20 20 A First Application // Source File : FirstApplicationTest.java import javax.swing.*; import javax.swing.event.*; class FirstApplication extends JFrame { public FirstApplication(String title) { super(title);// sets frame title getContentPane().add(new JLabel("Our first application !")); } } // End of class FirstApplication public 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 21 Concept Swing component class Application class Interface class presents component to user intercepts user interaction Instantiates Swing components Code to act upon user input ? Listener Object

22 22 Concept Swing component class Application class Listener Object 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 code of all registered listeners

23 23 Concept JTextField Application class Listener Object... JTextField f = new JTextField(20); Listen a = new Listen(); f.addActionListener(a); public void actionPerformed(ActionEvent e) { // … } ENTER PRESSED ActionEvent object

24 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 25 Listener options Option 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 !"); } Listener Object Registration Listener Class

26 26 Listener options Option 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 !"); } Listener Class Listener Object Registration

27 27 Listener options Option 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()); } } ); } Listener Object Listener Class Registration

28 28 Listener options Option 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); } Listener Object Listener Class Registration

29 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 Listener Object Listener Class

30 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 31 Listeners class 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 32 Many listeners Application object Swing object USER ACTION Event Object Listener object callback

33 33 Many listeners class 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 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 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 36 ONE listener Application object Swing object 1 USER ACTION Listener object Swing object 2 Swing object 3 Event Object 1 Event Object 2 Event Object 3 callback USER ACTION callback USER ACTION

37 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 38 ONE listener class 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 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 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 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 42 Dynamic event binding class 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 43 In general... Swing Components can fire Events Registered listener objects are called Listener objects implement agreed interface XxxEvent addXxxListener removeXxxListener XxxListener

44 44 In general... XxxEvent addXxxListener XxxListener Component JButton JCheckBox JFrame ActionEventItemEventWindowEvent addActionListener addItemListeneraddWindowListener ActionListenerItemListener WindowListener

45 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 46 Example : JFrame class 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 47 Adapter Classes Motivation 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 48 Adapter Classes Example : WindowListener 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 49 Adapter Classes Example : WindowListener Implementation with adapter 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 50 Adapter Classes Example : 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 51 Concept 3 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 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 53 Containers can hold other components creating a “containment” hierarchy components held controlled by add(…) remove(…) layout controlled by own layout manager setLayout(LayoutManager l); doLayout(); (force layouting)

54 54 Containers Construct a Swing application (without event handlers), showing following layout : JTextArea object

55 55 Containers Containment hierarchy JFrame Content Pane JPanel light JPanel buttons JTextArea a JButton green JButton orange JButton red

56 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 JButton green JButton orange JButton red

57 57 Forcing layout example 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 58 Forcing Layout Extend the previous example : add a remove button organize all buttons in 2 columns

59 59 Abstract Window Toolkit The awt-package Atomic components “containing” components

60 60 Events The awt.event-package

61 61 Awt - Swing connection 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 62 Swing Atomic awt-components Top-level Swing containers All other Swing components


Download ppt "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."

Similar presentations


Ads by Google