1 / 38

UI Programming in Java

UI Programming in Java. Part 4 – AWT Marc Abrams Virginia Tech CS Dept courses.cs.vt.edu/wwwtut/. Scripple Application. Menu bar: new, close, quit Pop-up menu: save, load, cut, paste, color, … Menu keyboard shortcuts Anonymous classes. Ex. 8-1: Scribble Frame.

Download Presentation

UI Programming in Java

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. UI Programming in Java Part 4 – AWT Marc Abrams Virginia Tech CS Dept courses.cs.vt.edu/wwwtut/ www.cs.vt.edu/wwtut/

  2. Scripple Application • Menu bar: new, close, quit • Pop-up menu:save, load, cut, paste, color, … • Menu keyboard shortcuts • Anonymous classes www.cs.vt.edu/wwtut/

  3. Ex. 8-1: Scribble Frame import java.awt.*; // ScrollPane, PopupMenu, MenuShortcut, etc. import java.awt.datatransfer.*; // Clipboard, Transferable,etc. import java.awt.event.*; // New event model. import java.io.*; // Object serialization streams. import java.util.zip.*; // Data compression/decomp. streams. import java.util.Vector; // To store the scribble in. import java.util.Properties; // To store printing preferences. www.cs.vt.edu/wwtut/

  4. Ex. 8-1 cont: Scribble Frame public class ScribbleFrame extends Frame { /** A very simple main() method for our program. */ public static void main(String[] args){ new ScribbleFrame(); } // Remember # of open windows so we can quit when last one is // closed protected static int num_windows = 0; public ScribleFrame() { /*constructor*/ }// other functions } www.cs.vt.edu/wwtut/

  5. Ex. 8-1 cont: Scribble Frame /** Create a Frame, Menu, and ScrollPane */ public ScribbleFrame() { super("ScribbleFrame"); // Create the window. num_windows++; // Count it. ScrollPane pane = new ScrollPane(); pane.setSize(300, 300); // Specify scrollpane size. this.add(pane, "Center"); // Add it to the frame. Scribble scribble; scribble = new Scribble(this, 500, 500); pane.add(scribble); // Add it to the ScrollPane www.cs.vt.edu/wwtut/

  6. Next let’s look at some awt.event classes needed… • To add menus, we’ll need some listener classes… www.cs.vt.edu/wwtut/

  7. http://www.ora.com/info/java/qref11/java.awt.event.WindowAdapter.htmlhttp://www.ora.com/info/java/qref11/java.awt.event.WindowAdapter.html CLASS java.awt.event.WindowAdapter Java in a Nutshell Online Quick Reference for Java 1.1 Availability: JDK 1.1 public abstract class WindowAdapter extends Object implements WindowListener { public void windowActivated(WindowEvent e); public void windowClosed(WindowEvent e); public void windowClosing(WindowEvent e); public void windowDeactivated(WindowEvent e); public void windowDeiconified(WindowEvent e); public void windowIconified(WindowEvent e); public void windowOpened(WindowEvent e); } www.cs.vt.edu/wwtut/

  8. http://www.ora.com/info/java/qref11/java.awt.event.ActionListener.htmlhttp://www.ora.com/info/java/qref11/java.awt.event.ActionListener.html CLASS java.awt.event.ActionListener Java in a Nutshell Online Quick Reference for Java 1.1 Availability: JDK 1.1 public abstract interface ActionListener extends EventListener { // Public Instance Methods public abstract void actionPerformed(ActionEvent e); } www.cs.vt.edu/wwtut/

  9. http://www.ora.com/info/java/qref11/java.awt.event.KeyEvent.htmlhttp://www.ora.com/info/java/qref11/java.awt.event.KeyEvent.html CLASS java.awt.event.KeyEvent Java in a Nutshell Online Quick Reference for Java 1.1 Availability: JDK 1.1 public class KeyEvent extends InputEvent { // Public Constructors public KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar); // Class Methods public static String getKeyModifiersText(int modifiers); public static String getKeyText(int keyCode); // Public Instance Methods public char getKeyChar(); public int getKeyCode(); public boolean isActionKey(); } www.cs.vt.edu/wwtut/

  10. http://www.ora.com/info/java/qref11/java.awt.MenuItem.html CLASS java.awt.MenuItem Java in a Nutshell Online Quick Reference for Java 1.1 Availability: JDK 1.0 public class MenuItem extends MenuComponent { // Public Constructors 1.1 public MenuItem(); public MenuItem(String label); 1.1 public MenuItem(String label, MenuShortcut s); } www.cs.vt.edu/wwtut/

  11. Ex. 8-1 cont: Scribble Frame MenuBar menubar = new MenuBar(); // Create a menubar. this.setMenuBar(menubar); // Add it to the frame. Menu file = new Menu("File"); // Create a File menu. menubar.add(file); // Add to menubar. // Create three menu items, with menu shortcuts, add to menu. MenuItem n, c, q; file.add(n = new MenuItem("New Window", new MenuShortcut(KeyEvent.VK_N))); file.add(c = new MenuItem("Close Window",new MenuShortcut(KeyEvent.VK_W))); file.addSeparator(); // Put a separator in the menu file.add(q = new MenuItem("Quit",new MenuShortcut(KeyEvent.VK_Q))); www.cs.vt.edu/wwtut/

  12. Ex. 8-1 cont: Scribble Frame // Create and register action listener objects for the three menu items. n.addActionListener(new ActionListener() { // Open a new windowpublic void actionPerformed(ActionEvent e) {new ScribbleFrame();}}); c.addActionListener(new ActionListener() { // Close this window. public void actionPerformed(ActionEvent e) {close();}}); www.cs.vt.edu/wwtut/

  13. Ex. 8-1 cont: Scribble Frame q.addActionListener(new ActionListener() { // Quit the program. public void actionPerformed(ActionEvent e) {System.exit(0);}}); // Another event listener, this one to handle window close requests. this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {close();}}); www.cs.vt.edu/wwtut/

  14. Ex. 8-1 cont: Scribble Frame // Set the window size and pop it up. this.pack(); this.show(); } /** Close a window. If this is the last open window, just quit. */ void close() { if (--num_windows == 0) System.exit(0); else this.dispose(); } } www.cs.vt.edu/wwtut/

  15. http://www.ora.com/info/java/qref11/java.awt.AWTEvent.html CLASS java.awt.AWTEvent Java in a Nutshell Online Quick Reference for Java 1.1 Availability: JDK 1.1 public abstract class AWTEvent extends EventObject { // Public Constructors public AWTEvent(Event event); public AWTEvent(Object source, int id); public int getID(); public String paramString(); } www.cs.vt.edu/wwtut/

  16. http://www.ora.com/info/java/qref11/java.util.Vector.html CLASS java.util.Vector Java in a Nutshell Online Quick Reference for Java 1.1 Availability: JDK 1.0 public class Vector extends Object implements Cloneable, Serializable { // Public Constructors public Vector(int initialCapacity, int capacityIncrement); public Vector(int initialCapacity); public Vector(); } www.cs.vt.edu/wwtut/

  17. Let’s look at class Scribble… • Allows drawing in colors via mouse events • Implements paint() • Implements pop-up menu(print, load/save, cut/copy/paste) www.cs.vt.edu/wwtut/

  18. Class Diagram for Scribble • See transparency www.cs.vt.edu/wwtut/

  19. Extends Component, not Canvas, making it "lightweight." Here’s how class Scribble starts… /** * This class is a custom component that supports scribbling. It also has * a popup menu that allows the scribble color to be set and provides access * to printing, cut-and-paste, and file loading and saving facilities. */ class Scribble extends Component implements ActionListener { protected short last_x, last_y; protected Vector lines = new Vector(256,256); protected Color current_color = Color.black; protected int width, height; protected PopupMenu popup; protected Frame frame; www.cs.vt.edu/wwtut/

  20. Scribble’s constructor (1 of 3) /** This constructor requires a Frame and a desired size */ public Scribble(Frame frame, int width, int height) { this.frame = frame; this.width = width; this.height = height; // We handle scribbling with low-level events, so we must // specify which events we are interested in. this.enableEvents(AWTEvent.MOUSE_EVENT_MASK); this.enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); www.cs.vt.edu/wwtut/

  21. Scribble’s constructor (2 of 3) // Create the popup menu using a loop. Note the separation of menu // "action command" string from menu label. Good for internationalization. String[] labels = new String[] { "Clear", "Print", "Save", "Load", "Cut", "Copy", "Paste" }; String[] commands = new String[] { "clear", "print", "save", "load", "cut", "copy", "paste" }; popup = new PopupMenu(); // Create the menu for(int i = 0; i < labels.length; i++) { MenuItem mi = new MenuItem(labels[i]); mi.setActionCommand(commands[i]); mi.addActionListener(this); popup.add(mi); // Add item to the popup menu. } www.cs.vt.edu/wwtut/

  22. Scribble’s constructor (3 of 3) Menu colors = new Menu("Color"); // Create a submenu. popup.add(colors); // And add it to the popup. String[] colornames = new String[] { "Black", "Red", "Green", "Blue"}; for(int i = 0; i < colornames.length; i++) { MenuItem mi = new MenuItem(colornames[i]); mi.setActionCommand(colornames[i]); mi.addActionListener(this); colors.add(mi); } // Finally, register the popup menu with the component it appears over this.add(popup); } www.cs.vt.edu/wwtut/

  23. Scribble.getPreferredSize() /** Specifies how big the component would like to be. Always returns the preferred size passed to the Scribble() constructor */ public Dimension getPreferredSize() { return new Dimension(width, height); } www.cs.vt.edu/wwtut/

  24. Scribble.actionPerformed() /** This is the ActionListener method invoked by the popup menu items */ public void actionPerformed(ActionEvent event) { // Get the "action command" of the event, and dispatch based on that. // This method calls a lot of the interesting methods in this class. String command = event.getActionCommand(); if (command.equals("clear")) clear(); else if (command.equals("print")) print(); else if (command.equals("save")) save(); else if (command.equals("load")) load(); else if (command.equals("cut")) cut(); else if (command.equals("copy")) copy(); else if (command.equals("paste")) paste(); else if (command.equals("Black")) current_color = Color.black; else if (command.equals("Red")) current_color = Color.red; else if (command.equals("Green")) current_color = Color.green; else if (command.equals("Blue")) current_color = Color.blue; } www.cs.vt.edu/wwtut/

  25. Scribble.paint() /** Draw all the saved lines of the scribble, in the appropriate colors */ public void paint(Graphics g) { for(int i = 0; i < lines.size(); i++) { Line l = (Line)lines.elementAt(i); g.setColor(l.color); g.drawLine(l.x1, l.y1, l.x2, l.y2); } } www.cs.vt.edu/wwtut/

  26. Scribble’s processMouseEvent /** * This is the low-level event-handling method called on mouse events * that do not involve mouse motion. Note the use of isPopupTrigger() * to check for the platform-dependent popup menu posting event, and of * the show() method to make the popup visible. If the menu is not posted, * then this method saves the coordinates of a mouse click or invokes * the superclass method. */ public void processMouseEvent(MouseEvent e) { if (e.isPopupTrigger()) // If popup trigger, popup.show(this, e.getX(), e.getY()); else if (e.getID() == MouseEvent.MOUSE_PRESSED) { last_x = (short)e.getX(); last_y = (short)e.getY(); } else super.processMouseEvent(e); } www.cs.vt.edu/wwtut/

  27. Scribble.clear() /** Clear the scribble. Invoked by popup menu */ void clear() { lines.removeAllElements(); // Throw out the saved scribble repaint(); // and redraw everything. } www.cs.vt.edu/wwtut/

  28. Activity for class • Find a partner and study class Scribble. • Answer the following… (Click here for javadocs, here for Scribble’s code.) • Why isn’t Scribble’s superclass java.awt.Frame? • In Scribble’s constructor, why are two String arrays needed (labels and commands) which contain the same 7 words? • Look at the call to EnableEvents() in Scribble’s constructor. • What class defines EnableEvents()? • Why doesn’t class ScribbleFrame need to enable the mouse events? • How many points does save write to a file? One per pixel? Or what? • How many bytes are written to the save file per point saved? • Estimate the biggest file created that menu save could create. Then run ScribbleFrame and check. • What sequence of events that occurs from the time the user clicks the right mouse button until the method associated with a popup menu item (e.g., method Scribble.print()) is called? Is processMouseEvent() called one time or two times? • Who calls getPreferredSize()? www.cs.vt.edu/wwtut/

  29. Let’s see how popup menu’s cut, copy, paste work… www.cs.vt.edu/wwtut/

  30. Java AWT Datatransfer • Supports underlying OS’s clipboard • Operations: copy, cut, paste • Handles one object at a time • Java 2 permits drag & drop • to/from non-Java apps • between Java apps • w/in one Java app (from jdk 1.1.x) www.cs.vt.edu/wwtut/

  31. JAVA AWT DATATRANSFER • 3 classes • Clipboard (provided by OS) • DataFlavor (flavor = mime type) • user defined class to put on system Clipboard (contains cut/copied data + DataFlavor) • 2 interfaces • Clipboard Owner • Transferable • 1 exception • UnsupportedFlavorException www.cs.vt.edu/wwtut/

  32. JAVA AWT DATATRANSFER • User class must implement two interfaces (ClipboardOwner and Transferable) and must • remembers an object • returns object • Clipboard Owner:notifies you when data is removed www.cs.vt.edu/wwtut/

  33. Instantiate DataFlavor public static final DataFlavor dataFlavor = new DataFlavor(Vector.class, "ScribbleVectorOfLines"); • We’ll put instances of Vector on clipboard www.cs.vt.edu/wwtut/

  34. Method cut() public void copy() { // Get system clipboard Clipboard c = this.getToolkit().getSystemClipboard(); // Copy and save the scribble in a Transferable object SimpleSelection s = new SimpleSelection(lines.clone(), dataFlavor); // Put that object on the clipboard c.setContents(s, s); } www.cs.vt.edu/wwtut/

  35. Method clear() /** Cut is just like a copy, except we erase the scribble afterwards */ public void cut() { copy(); clear(); } www.cs.vt.edu/wwtut/

  36. Class SimpleSelection (1 of 2) static class SimpleSelection implements Transferable, ClipboardOwner { protected Object selection; // The data to be transferred. protected DataFlavor flavor; // The one data flavor supported. public SimpleSelection(Object selection, DataFlavor flavor) { this.selection = selection; // Specify data. this.flavor = flavor; // Specify flavor. } … www.cs.vt.edu/wwtut/

  37. Class SimpleSelection (1 of 2) public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { flavor }; } public boolean isDataFlavorSupported(DataFlavor f) { return f.equals(flavor); } public Object getTransferData(DataFlavor f) throws UnsupportedFlavorException { if (f.equals(flavor)) return selection; else throw new UnsupportedFlavorException(f); } public void lostOwnership(Clipboard c, Transferable t) { selection = null; } } www.cs.vt.edu/wwtut/

  38. Method paste() • Does c.getContents(), where c is clipboard www.cs.vt.edu/wwtut/

More Related