1 / 77

Nota Bene

Nota Bene. This lecture presentation contains a number of "hidden" slides. Feel free to read, study and learn from them on your own! (I openned them all). Today's Plan for Fun. Events What is an event? Simple (?) Example Swing Components JFrames JComponents An example

zared
Télécharger la présentation

Nota Bene

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Nota Bene This lecture presentation contains a number of "hidden" slides. Feel free to read, study and learn from them on your own! (I openned them all)

  2. Today's Plan for Fun • Events • What is an event? • Simple (?) Example • Swing Components • JFrames • JComponents • An example • Swing Component Design (MVC/UI-Delegate)

  3. Events • Behind the scenes the Java runtime environment is monitoring lots of things • When any of a number of different things happen an event is said to occur. Sometimes the terminology is "An event gets fired" • Examples of the types of things that can "fire" events • Pressing a key on the keyboard • Clicking on a component (like a button) • Entering a component with the mouse pointer • Have a timer "time-out"

  4. Events • Moving the mouse around any reasonably complicated GUI can literally cause hundreds if not thousands of events to occur • They will be ignored except for the ones that you tell Java that you are interested in doing something about • Java maintains a data structure of all the events that you have decided to handle and looks up events and does what you tell it to do.

  5. Remember this??? import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { System.out.println ("About to make GUI"); Frame f = new Frame ("Hello GUIs"); f.setSize( 200, 200 ); f.show(); System.out.println ("Finished making GUI"); }// main }// class HelloGUI

  6. What didn't work???

  7. Making it work • Determine which event occurs when the "Close the Window" button is pressed • The API is your friend • The lecture notes are your friend • Hint: In this case it's an event called "Window Closing" • Decide what class is going to handle this event • It might be the actual class which has the window • It can be any other class • Write the method (and class?) that will handle the event. When this event occurs Java is going to go to the class that you identify as the event handler or Listener.It will look for a method called: public void windowClosing(WindowEvent e) • Jave will be sorely annoyed if this class doesn't have this method. How might the designers of Java guaranteed that you will implement this method?

  8. An Interface!!! // Note: found in java.awt.event public abstract interface WindowListener extends EventListener { void windowActivated(WindowEvent e); void windowClosed(WindowEvent e); void windowClosing(WindowEvent e); void windowDeactivated(WindowEvent e); void windowDeiconified(WindowEvent e); void windowIconified(WindowEvent e); void windowOpened(WindowEvent e); }

  9. So we could write a class like this import java.awt.*; import java.awt.event.*; public class Handler implements WindowListener { public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e) { Window w = e.getWindow(); w.setVisible(false); w.dispose(); System.exit(0); } public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} }

  10. Making it work II • Register the listener with Java. That is, tell Java in which class the method will be located to run when the Window Closing Event occurs.

  11. Registration import java.awt.*; public class HelloGUI { public static void main (String[ ] arg) { Handler h = new Handler(); System.out.println ("About to make GUI"); Frame f = new Frame ("Hello GUIs"); f.setSize( 200, 200 ); f.addWindowListener(h); f.show(); System.out.println("Finished making GUI"); } // main } // class HelloGUI

  12. Demonstration

  13. Diagramatically Class Pool class HelloGUI main { Frame f Handler h } class Frame class Handler Interface WindowAdapter Frame Instance Handler Instance

  14. Key Ideas • Determine which event occurs • Decide what class is going to handle this event • Write the method (and class?) that will handle the event. • Register the listener with Java.

  15. Questions? Very important that you understand this simple example to understand the concepts that follow.

  16. Potential Points of Perplexion • What exactly is the listener? Is it the component getting clicked on? • No, the listener is the object that contains the method that Java will call when the event happens. • You must tell the component getting clicked which object that is by registering: addWindowListener... • As we will see it could be the same!!! • How will I know what type of listener to use? • There are only so many • The API • Lecture/Instructor/Recitation/TA/etc. • Experience! • What about all those other window things (e.g. windowActivated) • We actually did implement them • We said: Don't do anything!

  17. Questions?

  18. Today's Plan for Fun • Events • What is an event? • Simple (?) Example • Swing Components • JFrames • JComponents • An example • Swing Component Design (MVC/UI-Delegate)

  19. Recall Earlier, we cautioned about the existence of two toolkits in Java for creating GUIs: AWT Swing Today, we examine a few Swing components. The goal is to learn how Swing components in general are designed, so that you can make better use of the API.

  20. That Which Swings In 1997, Sun announced a new graphical toolkit for Java called the “Java Foundation Classes”, or “JFC”. This term is usually pronounced “Swing”. The JFC/Swing classes provide well designed, powerful widgets for GUI developers. Let’s take a look . . .

  21. JFC/Swing “Now it gets interesting . . . “

  22. (De)Motivation 0.

  23. Historical Problems with AWT WinNT ButtonPeer File Edit Help java.awt.Button MacOS ButtonPeer CLICK ME ButtonPeer AWT components required native “peer” methods to render and operate--many steps! Motif ButtonPeer Slow & Inflexible! • All AWT components required runtime peer resources • slow on some platforms (notably Windows) • portability problems (slightly different look, some behaviors different) • least common denominator phenomenon: If one OS (e.g., Windows) did not support a widget, the entire AWT had to suffer without it. • Limited AWT widget library • addressed somewhat by JDK 1.1b3+, which allowed subclassing of components, or “lightweights”

  24. Stop-gap remedies for JDK 1.1b3+ (Layering of components requires layout subclasses) (Menu bars limited; no images possible without *extensive* simulation through components) File Edit Help (Tooltips required threads, window subclasses & extensive event handling) (Image buttons required component subclassing, methods to handle ‘click’ look, as well as event handlers) CLICK ME Tooltip • Developers avoided a few AWT limitations through: • Pervasive use of lightweights • e.g., tooltip simulation through threads/windows/components • extensive coding around rigid look • use of layered gifs Bottom line: Making stuff look cool or satisfying a clients request could be a nightmare!

  25. Introducing Swing/JFC javax.swing.JButton File Edit Help CLICK ME • Sun addressed problems with Java Foundation Classes (JFC) a/k/a Swing • Key elements: • No reliance on native peers; the JVM does the work, and is faster • Swing completely controls look and feel of all components: • PLAF, or “pluggable look and feel” • Superior design: Fast, flexible, extensible!

  26. Swing Packages • All the new Swing components and classes need a home. Where? • A subject of great debate! • For JDK 1.1, Sun used “com.sun.java.swing”; developers revolted(başkaldırmak). • Problem: developers complained this “com” designation was not appropriate for “core” class--something part of language. Solution: Why “javax”? * logical grouping * minimizes transition costs * most developers happy with it * helps maintain existing JDK 1.1 code (cf. MFC lib breaks) javax.swing.* Denotes ‘extension’ package that has migrated to core status

  27. Overview of JFC/Swing Packages • javax.swing • javax.swing.table • javax.swing.tree • javax.swing.border • javax.swing.colorchooser • javax.swing.filechooser • javax.swing.event • javax.swing.undo • javax.swing.plaf • javax.swing.plaf.basic • javax.swing.plaf.metal • javax.swing.plaf.multi • javax.swing.text • javax.swing.text.html • javax.swing.text.html.parser • javax.swing.text.rtf

  28. Overview of the Overview Components, including “aggregate” or complex components Packages to control the “look and feel” of Swing Text-based widgets (including html/rtf display) New event packages

  29. Getting into the Swing AWT Swing Classes JDK 1.2 • Download from www.javasoft.com • Swing works with JDK 1.1 and JDK 1.2 • JDK 1.1 requires “swingall.jar” file in the CLASSPATH • For JDK 1.2, it’s in the soup (no CLASSPATH settings) • JDK 1.2 will also run all JDK 1.1 code (~ 20% faster!) • Thus, even older JDKs can make use of Swing, with a CLASSPATH setting. import com.sun.java.swing.*; import javax.swing.*; AWT JDK 1.1 classpath swingall.jar

  30. Short Examples 1.

  31. Short Example: Old AWT import java.awt.*; public class HelloWorld extends Frame { public Button bOld; //public Panel p; public HelloWorld() { bOld = new Button ("Good Bye"); //p = new Panel(); //p.add(bOld); //this.add(p); this.add(bOld); /* note the addition directly to the Frame */ this.pack(); } public static void main(String arg[]){ /* note lack of listener; this is a demo */ new HelloWorld().show(); } }// class HelloWorld We comment most of this out for now; AWT lets us add directly to the Frame.

  32. Hello Swing, Good Bye AWT Note Swing components import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloWorld extends JFrame { Button bOld; public JButton bNew; public JPanel p; public HelloWorld() { bNew = new JButton("Hello"); bOld = new Button ("Good Bye"); p = new JPanel(); p.add(bNew); p.add(bOld); this.getContentPane().add(p); this.pack(); } public static void main(String arg[]){ new HelloWorld().show(); } }// class HelloWorld Note addition of components to JPanel’s ‘content pane’ SEE CAUTIONARY NOTE RE: Mixing light and heavyweight components!

  33. What’s the Big Deal? • HelloWorld looks similar to AWT. Why switch to JFrame, JButton, JPanel, etc? • Benefits: • speed • lightweight flexibility (transparency, non-rectangular shape) • pluggable look and feel • automatic double buffering with many J- components. • additional functionality (e.g., tooltips, etc.) I’m lightweight, pluggable, extensible and fast. The VM draws me. I need Windows™ to be visible and ‘toggle’. I’m slow.

  34. Widget Example: JButtons • The java.swing.JButton class implements a “state version” of a java.swing.AbstractButton. Many methods come from the abstract class: • A variety of constructors (Strings, Icons, etc.); • setRolloverEnabled(boolean); • setIcon(Icon); • setRolloverIcon(Icon); • setActionCommand(String); -- an extra String tacked onto the event that gets fired! • setContentAreaFilled(boolean) -- transparency for icons! • setModel(ButtonModel); -- sets the ‘type’ of Button (you can define your own Button behaviors!) • setMnemonic(char/int); -- set mnemonics for button Lesson: Check the API for useful behaviors.

  35. Cool Buttons Images from disk: import javax.swing.*; public class HelloWorld2 extends JFrame { public JButton bNew; public JPanel p; public HelloWorld2() { bNew = new JButton("New Document", new ImageIcon("Document.gif")); bNew.setRolloverEnabled(true); bNew.setRolloverIcon (new ImageIcon ("New.gif")); p = new JPanel(); p.add(bNew); getContentPane().add(p); this.pack(); } public static void main(String arg[ ]) { new HelloWorld2().show(); } }// class HelloWorld2 Sets icon and rollover Icon. Note: Icon constructor took String argument, and automatically loaded image

  36. Demonstration

  37. Why getContentPane() ? • The HelloWorld example required us to call getContentPane() before “add()”ing an object to the JFrame: myFrameInstance.getContentPane().add(myComponent); Required of JFrame, JDialog and JInternalFrame instances Usually “this” E.g., “myJButton” • This differs from traditional AWT container additions, were we simply call “add”, passing in the component. • Let’s cut a JFrame open to find out why . . .

  38. A JFrame Autopsy JLayeredPane Menu ContentPane JPanel A java.awt.Frame is composed of a single container--the Frame object itself. It is flat as a pop tart. A javax.swing.JFrame is composed of a transparent “glassPane” surface, and an inner Jpanel with Contents and Menu click click “The Pop Tart / Sandwich Duality”

  39. JFrame Class View Component AWT Frame GlassPane Container contains manages ContentPane JComponent JFC contains JMenuBar manages JRootPane JFrame contains contains The JRootPane is a container with a JLayeredPane (holding the Menu and ContentPane) and a Component GlassPane. It serves as base for numerous classes. contains JLayeredPane

  40. JRootPane: The Content Pane The JRootPane contains only two components: the JLayeredPane and the ComponentGlassPane Its layout manager ignores all attempts to add new components. Instead, one must add to the JRootPane’sContentPane, found inside the JLayeredPane. A call to getContentPane() returns an instance of the ContentPane.

  41. JRootPane: The Glass Pane JFrame Blue Print public Component getGlassPane(); public void setGlassPane(Component); We can use the top “glassPane” as a drawing area. Since it spans the entire JFrame, we can draw on top of menu bars, and every component. The JPanel has a remarkable layering feature, allowing us to stack and shuffle components. public JPanel getContentPane();

  42. JFrame Disposal • JFrame allows you to configure how it responds to closure. • Default: hides JFrame on closure attempt. • To modify: invoke setDefaultCloseOperation(). • E.g.,: MyJFrameInstance.setDefaultCloseOperation (WindowConstants.DO_NOTHING_ON_CLOSE); /* behaves just like java.awt.Frame */ • other constants in javax.swing.WindowConstants: • HIDE_ON_CLOSE - invokes any registered WindowListener objects, then hides. This is default behavior. • DISPOSE_ON_CLOSE - invokes any registered WindowListener objects, and then disposes.

  43. Questions?

  44. Questions?

  45. JComponent: The Generic Widget • The JComponent provides the basis for all Swing components. • JComponent extends java.awt.Container, making all Swing components large, powerful widgets. (Also, all Swing components are also containers--even if you wouldn’t normally place things in them. E.g., JButton) • In turn, JComponent is subclassed by numerous widgets. Thus, composition is favored or inheritance for widget manipulation.

  46. JComponent Since JComponent is the basis for most Swing components, all Swing widgets have the following general features: Borders -- JComponent derived classes can have borders Accessibility -- JComponents use Swing’s accessibility features to provide additional information about the widget. Tooltips -- JComponents can have time sensitive tooltips. Double Buffering -- By default, Swing components have double buffering built in Serialization -- Ability to save state to a file.

  47. Demo: A GlassPane Example import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GlassDemo extends JFrame implements ActionListener { private boolean bGlassVisible; private GlassPanel glass; private JButton button; This demo will not be covered in class; it is provided as an example of how to work with JFrames. Here’s a simple example that shows how to use aspects of JFrames. Frist, we make a JFrame subclass. We declare some instance variables: a GlassPanel (described later), a boolean flag for the glass panel’s visibility, and a JButton to toggle

  48. Glass Panel Example import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GlassDemo extends JFrame implements ActionListener { private boolean bGlassVisible; private GlassPanel glass; private JButton button; public void actionPerformed (ActionEvent e){ bGlassVisible = !bGlassVisible; glass.setVisible(bGlassVisible); } The actionPerformed method merely toggles the visibility of the glass pane

  49. Glass Panel Example import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GlassDemo extends JFrame implements ActionListener { private boolean bGlassVisible; private GlassPanel glass; private JButton button; public void actionPerformed (ActionEvent e){ bGlassVisible = !bGlassVisible; glass.setVisible(bGlassVisible); } public void centerInScreen(){ Toolkit tk = Toolkit.getDefaultToolkit(); Dimension d = tk.getScreenSize(); this.setLocation((d.width-getSize().width)/2, (d.height-getSize().height)/2); } ... A little magic. (It merely centers the frame in the screen.)

  50. Glass Panel Example import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GlassDemo extends JFrame implements ActionListener { private boolean bGlassVisible; private GlassPanel glass; private JButton button; public void actionPerformed (ActionEvent e){ bGlassVisible = !bGlassVisible; glass.setVisible(bGlassVisible); } public void centerInScreen(){ Toolkit tk = Toolkit.getDefaultToolkit(); Dimension d = tk.getScreenSize(); this.setLocation((d.width-getSize().width)/2, (d.height-getSize().height)/2); } public static void main(String[] args) { new GlassDemo().show(); } A simple test main

More Related