copyright © 2002, systems and computer engineering, carleton university. 94.204-18b-gui2.ppt 1...
TRANSCRIPT
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
1
94.204* Object-Oriented Software Development
Part 18-b
Building Graphic User Interfaces with Java
Files discussed in these slides:
• MouseDemo1.java
• MouseDemo2.java
• MouseDemo3.java
• LinearRegression1.java
• revised March 2002
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
2
Problem: Curve Fitting
• Consider the problem of plotting a straight line through a set of points
• The equation of the line can be determined by using a technique called linear regression (method of least squares)
• Given a set of n points (x0, y0), (x1, y1), …(xn-1, yn-1) the equation of the “best-fit” straight line through the points is:
y = mx + b
where:
m = (Σ(xiyi) - Σxi * Σ yi / n) / (Σ(xi2) - (Σxi)2 / n)
b = (Σyi - m * Σxi) / n
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
3
Problem: Curve Fitting
• Deriving the equations for the slope and y-intercept as a function of the (x,y) points isn’t difficult, but students sometimes have difficulty relating the equations to the line that they plot on a piece of paper
• Why not build an interactive GUI-based Java application that demonstrates the method of least squares?
• There are .java example files to accompany these slides
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
4
Problem: Curve Fitting
1. When the program runs, it will display an empty window
2. Each time you click the mouse in the frame, a circle is drawn at that point
3. As each point is clicked, the "best-fit" straight line through the set of points is calculated and drawn
– See the screen snapshots on the next two slides
• To build this application, we need to learn
– how to get input from the mouse
– how to draw circles and lines in a window
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
5
No points clicked One point clicked
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
6
Ten points clickedTwo points clicked
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
7
Handling Mouse Events
• Let’s look at three versions of an application that listens for mouse events within the frame
• Each time a mouse event occurs, details of the event are printed on System.out
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
8
MouseDemo1.java: UML Class Diagram
MouseListener
MouseMotionListener
CloseableFrame
MouseDemo1
MyMouseMotionHandler
MyMouseHandler
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
9
Listener Objects
• The frame (a MouseDemo1 object) is a source of MouseEvent events, which are generated when the mouse is in the frame
• Two listener objects are required to receive these events
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
10
Listener Objects
1. An instance of MyMouseHandler receives the events that are sent when the mouse enters or exits the frame, or is pressed, released, or clicked within the frame
• Class MyMouseHandler implements the 5 methods in the MouseListener interface:
public void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
public void mouseReleased(MouseEvent e);
public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
11
Listener Objects
2. An instance of MyMouseMotionHandler receives the events that are generated with the mouse is moved or dragged
• Class MyMouseMotionHandler implements the 2 methods in the MouseMotionListener interface:
public void mouseMoved(MouseEvent e);
public void mouseDragged(MouseEvent e);
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
12
Registering the Listener Objects With the Window
• Through inheritance, a MouseDemo1 object is a JFrame• The two listener objects must be registered with the frame
before they can receive events from the frame • MouseDemo1() creates the listener objects and registers
them with the frame, by sending addMouseListener and addMouseMotionListener messages to itself, passing references to the listener objects as arguments :
this.addMouseListener(new MyMouseHandler());this.addMouseMotionListener(new MyMouseMotionHandler());
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
13
Responding To Mouse Presses
• When the mouse button is pressed inside the frame, the frame dispatches a mouse event by sending the mousePressed() message to its MouseListener object, passing it a reference to the MouseEvent object
public void mousePressed(MouseEvent e){ System.out.println("mouse pressed @ (" + e.getX() + ", " + e.getY() + " )");}
• e.getX() and e.getY() return the coordinates of the mouse when the mouse button was pressed
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
14
Using a Single Listener Object
• We could simplify MouseDemo1 to use a single listener object that implements both listener interfaces:
class MyMouseHandler implements MouseListener,MouseMotionListener{ /* defines the 7 mouseXXX methods */ }
• We would also have to change MouseDemo1():MyMouseHandler ml =
new MyMouseHandler();this.addMouseListener(ml);this.addMouseMotionListener(ml);
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
15
MouseDemo2.java
• Java 2 lets us simplify things even further
• javax.swing.event provides interface MouseInputListener, which combines Java 1.1’s two mouse listener interfaces:
public abstract interface MouseInputListenerextends MouseListener, MouseMotionListener
• see MyMouseDemo2.java– MyMouseInputHandler implements the MouseInputListener interface
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
16
MouseDemo2.java: UML Class Diagram
MouseInputListener
CloseableFrame
MouseDemo2
MyMouseInputHandler
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
17
MouseDemo3.java
• How would we change the previous example to handle only mouse clicks, presses, and releases?
• mouseClicked(), mousePressed(), and mouseReleased() would be unchanged
• Because MyMouseInputHandler must implement all the methods in the MouseInputListener interface, it must provide "empty" methods for the methods that aren’t of interest:
public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mouseDragged(MouseEvent e) {}public void mouseMoved(MouseEvent e) {}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
18
Mouse Adapter Classes
• Implementing empty methods is tedious
• java.awt.event and javax.swing.event provide three abstract adapter classes that implement the three mouse listener interfaces
– each adapter class provides empty bodies for all the methods in the interface that it implements
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
19
Mouse Listener Interfaces and Adapter Classes
MouseListener
MouseMotionListener
MouseMotionAdapter
MouseAdapterMouseInputListener
MouseInputAdapter
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
20
The MouseInputAdapter Class
public abstract class MouseInputAdapter
extends Object
implements MouseInputListener {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
21
Using Adapter Classes in MouseDemo3.java
• To implement a MouseInputListener class, subclass MouseInputAdapter and override the methods of interest:
class MyMouseInputHandler extends MouseInputAdapter{ public void mouseClicked(MouseEvent e) { /* handle mouse click */ } public void mousePressed(MouseEvent e) { /* handle mouse press */ } public void mouseReleased(MouseEvent e) { /* handle mouse release */ }}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
22
MouseDemo3.java: UML Class Diagram
CloseableFrame
MouseDemo3
MyMouseInputHandler MouseInputAdapter
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
23
Designing The Curve Fitting Application
• We now know how our curve-fitting program will handle mouse input
– a listener object will listen for mouse clicks in the window
– for each click, the listener will get the coordinates of the mouse (by sending messages to the MouseEvent object) and save them
– the method of least squares will be used to calculate the slope and y-intercept of the straight line through the points
• How do we plot the points and the line in the window?
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
24
Displaying Information in a JFrame
• It is considered poor practice to draw in a JFrame• Instead, we create a panel object, add it to the frame, and
draw on the panel
• In Swing, panels are instances of class JPanel• JPanel objects
– have a drawing surface
– are containers (which means we can put GUI components in a JPanel)
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
25
Structure of a JFrame object
Title JFrame
JRootPane
JLayeredPane
optional menu bar
content pane
glass pane
Adapted from Core Java 1.2,Volume 1 - Fundamentals,Horstmann & Cornell
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
26
Adding Components to a JFrame
• A JFrame consists of 4 panes
• Components are added to the content pane
• To add a JPanel object to a JFrame:
// assume that f refers to a JFrame
…
JPanel p = new JPanel();
Container contentPane = f.getContentPane();
contentPane.add(p);
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
27
Drawing in a JPanel
• JPanel is a subclass of JComponent• JComponent defines paintComponent(), which is
invoked by the Java windowing system to draw in the component
• Subclasses of JComponent must override paintComponent() to provide appropriate painting behaviour for the subclass
• So, we need to define a class that extends JPanel and overrides paintComponent() to draw the points and the straight line
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
28
First Cut at the Curve Fitting Application
CloseableFrame
LinearRegression1
JPanel
Plot
paintComponent()
Draws points andthe straight line inthe panel
Vector
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
29
First Cut at the Curve Fitting Application
• LinearRegression1 is the application’s top-level window (frame)
• It creates a Plot object (which is-a JPanel), and adds the panel to the frame’s content pane
• Plot overrides paintComponent()
• To fulfill its responsibilities, paintComponent() needs to know
– the coordinates of each point where a mouse click occurs
– the slope and y-intercept of the line
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
30
First Cut at the Curve Fitting Application
• Assume that each time the mouse is pressed, the listener object for mouse events (not shown on the UML diagram) will get the mouse coordinates, store them in a Point object, and save the Point in a list (a Vector)
• paintComponent() will obtain the points from the Vector, draw them, calculate the best-fit straight line by using the method of least squares, and draw the line
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
31
Skeleton of Class Plot
class Plot extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Enumeration e = points.elements();
while (e.hasMoreElements()) {
Point p = (Point)e.nextElement();
g.drawOval(…);
}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
32
Skeleton of Class Plot
// need at least 2 points to plot a line
if (points.size() < 2)
return;
// Calculate the slope and y-intercept
// of the "best-fit" line.
calculateRegression();
g.drawLine(...);
}
private Vector points = new Vector();
private double m; // slope of the line
private double b; // y-intercept
}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
33
The Graphics Class
• paintComponent() is passed a reference to a Graphics object
• A Graphics object is a device-independent interface to the computer's graphics display
• Most of its methods are concerned with drawing shapes (filled and unfilled), and managing fonts and colours
• paintComponent() sends the Graphics object– the drawOval() message, to draw each point – the drawLine() message, to draw the straight line
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
34
Some Graphics Methods
• drawString() • drawOval(), fillOval() • drawRect(), fillRect(), clearRect() • drawRoundRect(), fillRoundRect() • draw3DRect(), fill3DRect() • drawArc(), fillArc() • drawPolygon(), fillPolygon() • drawPolyline()
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
35
Arranging for Mouse Input
• The mouse is clicked inside the panel, so Plot needs a MouseInputListener object (a MouseListener object would also do the job)
– we’ll subclass MouseInputAdapter• Plot’s constructor will create the mouse listener object
and register it with the panel
• Each time the mouse is pressed, mousePressed() will get the mouse coordinates, store them in a Point object, and save the Point in the Vector used by paintComponent()
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
36
Second Cut at the Curve Fitting Application
CloseableFrame
LinearRegression1
JPanel
Plot
paintComponent()
MyMouseInputHandlerMouseInputAdapter
Vector
mousePressed()
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
37
Skeleton of Class Plot
class Plot extends JPanel
{
public Plot()
{
MyMouseInputHandler ml =
new MyMouseInputHandler(this, points);
this.addMouseListener(ml);
}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
38
Skeleton of Class Plot
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Enumeration e = points.elements();
while (e.hasMoreElements()) {
Point p = (Point)e.nextElement();
g.drawOval(…);
}
// need at least 2 points to plot a line
if (points.size() < 2)
return;
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
39
Skeleton of Class Plot
// Calculate the slope and y-intercept
// of the "best-fit" line.
calculateRegression();
g.drawLine(...);
}
private Vector points = new Vector();
private double m; // slope of the line
private double b; // y-intercept
}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
40
Skeleton of Class MyMouseInputHandler
class MyMouseInputHandler
extends MouseInputAdapter
{
private JPanel panel;
private Vector points;
public MyMouseInputHandler(JPanel p, Vector v)
{
panel = p;
points = v;
}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
41
Skeleton of Class MyMouseInputHandler
public void mousePressed(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
points.addElement(new Point(x,y));
// Update the display.
panel.repaint();
}
}
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
42
Invoking paintComponent()
• The panel must be redrawn each time the mouse is clicked, so you might expect mousePressed() to send the paintComponent() message to Plot, but this is not what happens
• To force the screen to be repainted, send the repaint() message to the panel
• repaint() will invoke the paintComponent() method for all components that should be displayed
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
43
Eliminating References Between Objects
• Notice that mousePressed() sends the addElement() message to the Plot object’s Vector, and the repaint() message to the Plot object
• That’s why Plot() passes a reference to itself and a reference to its Vector to MyMouseInputHandler’s constructor, which saves the references for use by mousePressed()
• Aside: do we need both references? Could we eliminate the reference to the Vector object? Could we eliminate the reference to the Plot object? Could we eliminate both references?
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
44
Inner Classes
• An inner class is a class defined inside another class
• An object of an inner class can access the variables of the object that created it
• In the curve fitting program, class MyMouseInputHandler will be defined as a private inner class within class Plot
• The MyMouseInputHandler object can access the variables of the Plot object that created it
– it can access the Plot’s Vector object directly, as if the reference to the Vector was defined in class MyMouseInputHandler
Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-18b-Gui2.ppt
45
Skeleton of Inner Class MyMouseInputHandler
private class MyMouseInputHandlerextends MouseInputAdapter{ public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); points.addElement(new Point(x,y)); // equivalent to: //Plot.this.points.addElement(new Point(x,y)); repaint(); // equivalent to: // Plot.this.repaint(); }}