Download Part4 - Virginia Tech

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
UI Programming in Java
Part 4 – AWT
Marc Abrams
Virginia Tech CS Dept
courses.cs.vt.edu/wwwtut/
9/21/99
www.cs.vt.edu/wwtut/
1
Scripple Application




Menu bar: new, close, quit
Pop-up menu:
save, load, cut, paste, color, …
Menu keyboard shortcuts
Anonymous classes
9/21/99
www.cs.vt.edu/wwtut/
2
Ex. 8-1: Scribble Frame
import
import
import
import
import
import
import
9/21/99
java.awt.*; // ScrollPane, PopupMenu, MenuShortcut, etc.
java.awt.datatransfer.*; // Clipboard, Transferable,etc.
java.awt.event.*; // New event model.
java.io.*; // Object serialization streams.
java.util.zip.*; // Data compression/decomp. streams.
java.util.Vector; // To store the scribble in.
java.util.Properties; // To store printing preferences.
www.cs.vt.edu/wwtut/
3
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
}
9/21/99
www.cs.vt.edu/wwtut/
4
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
9/21/99
www.cs.vt.edu/wwtut/
5
Next let’s look at some
awt.event classes needed…

To add menus, we’ll need some listener
classes…
9/21/99
www.cs.vt.edu/wwtut/
6
http://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
public
public
public
public
public
public
void
void
void
void
void
void
void
windowActivated(WindowEvent e);
windowClosed(WindowEvent e);
windowClosing(WindowEvent e);
windowDeactivated(WindowEvent e);
windowDeiconified(WindowEvent e);
windowIconified(WindowEvent e);
windowOpened(WindowEvent e);
}
9/21/99
www.cs.vt.edu/wwtut/
7
http://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);
}
9/21/99
www.cs.vt.edu/wwtut/
8
http://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();
}
9/21/99
www.cs.vt.edu/wwtut/
9
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);
}
9/21/99
www.cs.vt.edu/wwtut/
10
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)));
9/21/99
www.cs.vt.edu/wwtut/
11
Ex. 8-1 cont: Scribble Frame
// Create and register action listener objects for the three menu items.
n.addActionListener(new ActionListener() {
// Open a new window
public void actionPerformed(ActionEvent e)
{new ScribbleFrame();}
});
c.addActionListener(new ActionListener() {
// Close this window.
public void actionPerformed(ActionEvent e)
{close();}
});
9/21/99
www.cs.vt.edu/wwtut/
12
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();}
});
9/21/99
www.cs.vt.edu/wwtut/
13
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();
}
}
9/21/99
www.cs.vt.edu/wwtut/
14
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();
}
9/21/99
www.cs.vt.edu/wwtut/
15
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();
}
9/21/99
www.cs.vt.edu/wwtut/
16
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)
9/21/99
www.cs.vt.edu/wwtut/
17
Class Diagram for Scribble

See transparency
9/21/99
www.cs.vt.edu/wwtut/
18
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.
*/
Extends Component, not Canvas, making it "lightweight."
class Scribble extends
protected short
protected Vector
protected Color
protected int
protected PopupMenu
protected Frame
9/21/99
Component implements ActionListener {
last_x, last_y;
lines
= new Vector(256,256);
current_color = Color.black;
width, height;
popup;
frame;
www.cs.vt.edu/wwtut/
19
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);
9/21/99
www.cs.vt.edu/wwtut/
20
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.
}
9/21/99
www.cs.vt.edu/wwtut/
21
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);
}
9/21/99
www.cs.vt.edu/wwtut/
22
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);
}
9/21/99
www.cs.vt.edu/wwtut/
23
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;
9/21/99
}
www.cs.vt.edu/wwtut/
24
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);
}
}
9/21/99
www.cs.vt.edu/wwtut/
25
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);
}
9/21/99
www.cs.vt.edu/wwtut/
26
Scribble.clear()
/** Clear the scribble.
Invoked by popup menu */
void clear() {
lines.removeAllElements(); // Throw out the saved scribble
repaint();
// and redraw everything.
}
9/21/99
www.cs.vt.edu/wwtut/
27
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.
1.
2.
3.
1.
2.
4.
5.
6.
7.
8.
9/21/99
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/
28
Let’s see how popup menu’s
cut, copy, paste work…
9/21/99
www.cs.vt.edu/wwtut/
29
Java AWT Datatransfer




Supports underlying OS’s clipboard
Operations: copy, cut, paste
Handles one object at a time
Java 2 permits drag & drop



9/21/99
to/from non-Java apps
between Java apps
w/in one Java app (from jdk 1.1.x)
www.cs.vt.edu/wwtut/
30
JAVA AWT DATATRANSFER

3 classes




2 interfaces



Clipboard (provided by OS)
DataFlavor (flavor = mime type)
user defined class to put on system Clipboard
(contains cut/copied data + DataFlavor)
Clipboard Owner
Transferable
1 exception

9/21/99
UnsupportedFlavorException
www.cs.vt.edu/wwtut/
31
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
9/21/99
www.cs.vt.edu/wwtut/
32
Instantiate DataFlavor
public static final DataFlavor dataFlavor = new
DataFlavor(Vector.class, "ScribbleVectorOfLines");

We’ll put instances of Vector on clipboard
9/21/99
www.cs.vt.edu/wwtut/
33
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);
}
9/21/99
www.cs.vt.edu/wwtut/
34
Method clear()
/** Cut is just like a copy, except we erase the
scribble afterwards */
public void cut() { copy(); clear();
9/21/99
www.cs.vt.edu/wwtut/
}
35
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.
}
…
9/21/99
www.cs.vt.edu/wwtut/
36
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;
}
}
9/21/99
www.cs.vt.edu/wwtut/
37
Method paste()

Does c.getContents(), where c is clipboard
9/21/99
www.cs.vt.edu/wwtut/
38