Upload
truongkien
View
233
Download
1
Embed Size (px)
Citation preview
Advanced Java Programming / © Shmulik London 2006Interdisciplinary Center Herzeliza Israel 1
Advanced Java Programming
Shmulik London
GUI Programming
Part I – AWT & Basics
Lecture #5
Advanced Java Programming / © Shmulik London 2006 2
Agenda
• AWT & Swing
• AWT components
• Containers
• Layout Managers
• Event Handling
• Painting
Advanced Java Programming / © Shmulik London 2006 3
AWT & Swing
• Originally Java came with the AWT (Abstract Window Toolkit)
• AWT was very basic. Developers wanted more.
• Swing is a much richer API for GUI.
• They are built around different design concept
• AWT and Swing co-exist now, but you normally use Swing.
Advanced Java Programming / © Shmulik London 2006 4
AWT
• AWT meant to be small and simple
– Allow easy porting to many platforms
– Developing GUI platform is a lot of effortJDK1.1 AWT – 141 files, 13262 lines of codeJDK1.5 AWT+Swing – 1017 files, 209,908 lines!!JDK1.1 was light – 8Mb compared to 55Mb today
• It was built around the concept that the GUI should have the look & feel of underlying platform
– A problematic concept for complex thing as GUI
Advanced Java Programming / © Shmulik London 2006 5
Concept behind AWT
• Use underlying widgets of platform
• Each component in AWT is just a wrapper for an underlying native widget (its peer)
• The component request the windowing system to create the underlying widget and customize it according to its properties
• Can support only lowest common denominator of all platforms
� Good performance� Easy to port JDK
� Native look & feel
Too elementaryHeavy weight components
Difficult to write apps thatwill look good on different
platforms
Advanced Java Programming / © Shmulik London 2006 6
Some AWT components
Button
TextField
Label
Scrollbar
Choice
Frame
others ....
Advanced Java Programming / © Shmulik London 2006 7
Class component
Component
TextComponentButton
• All components are derived from the class java.awt.Component
TextFieldTextArea
...
Advanced Java Programming / © Shmulik London 2006 8
Class Component
• Class component defines the properties common to all components: location, size, background color, foreground color, visibility, ...
public Dimension getSize()
public void setSize(Dimension d)
public void setSize(int x, int y)
public Point getLocation()
public void setLocation(Point p)
public void setLocation(int x, int y)
public Color getBackground()
public void setBackground(Color c)
...
Advanced Java Programming / © Shmulik London 2006 9
Container
• Container is a subclass of Component that is a superclass for all Components that can contain other components.
• It adds to Component the functionality of adding/removing components
public void add(Component c)
public void remove(Component c)
public Component[] getComponents()
public int getComponentCount()
public void setLayout(...)
...
Advanced Java Programming / © Shmulik London 2006 10
Opening a Frame
// A sample program that opens a yellow frame
class FrameExample {
public static void main(String[] args) {
Frame frame = new Frame(“Example”);
frame.setSize(400,300);
frame.setBackground(Color.yellow);
frame.setVisible(true);
}
}
Advanced Java Programming / © Shmulik London 2006 11
Opening a Frame
// A sample program that opens a yellow frame
class FrameExample {
public static void main(String[] args) {
new SampleFrame().setVisible(true);
}
}
class SampleFrame extends Frame {
public SampleFrame() {
super(“Example”);
setSize(400,300);
setBackground(Color.yellow);
}
}
Advanced Java Programming / © Shmulik London 2006 12
Adding components
// A sample program that opens a frame with
// a button on it
class FrameExample extends Frame{
public FrameExample () {
setSize(400,300);
Button okButton = new Button(“OK”);
add(okButton);
}
public static void main(String[] args) {
new FrameExample().setVisible(true);
}
}
Advanced Java Programming / © Shmulik London 2006 13
Layout Managers
• Were are the components added?
• There are two ways to layout components on a container:
– Set the exact size and location of every component
– Use a LayoutManager
• Every container has its own LayoutManagerobject
• The LayoutManager is responsible for the the layout of the component inside the container
• The LayoutManager is consulted whenever there is a need to rearrange the components inside the container (container size changed, component added.. )
Advanced Java Programming / © Shmulik London 2006 14
Layout Managers
Frame
FlowLayout
add(new Button(“Ok”))
layoutContainer(this)
Advanced Java Programming / © Shmulik London 2006 15
Layout Managers
• There a various types of Layout Managers. Each has its strategy for arranging the components.
• Layout managers given with java.awt:– FlowLayout, BorderLayout, GridLayout, CardLayout,
GridBagLayout
• You can define your own layout managers by implementing the interface java.awt.LayoutManager
• LayoutManager is an example of the Strategy pattern
Advanced Java Programming / © Shmulik London 2006 16
FlowLayout
setLayout(new FlowLayout());
add(new Label(“Name:”));
add(new TextField(10));
add(new Button(“Ok”));
Advanced Java Programming / © Shmulik London 2006 17
GridLayout
setLayout(new GridLayout(2,2));
add(new Button(“A”));
add(new Button(“B”));
add(new Button(“C”));
add(new Button(“D”));
Advanced Java Programming / © Shmulik London 2006 18
GridLayout
setLayout(new BorderLaout());
add(new Button(“North”), BorderLayout.NORTH);
add(new Button(“East”), BorderLayout.EAST);
add(new Button(“South”), BorderLayout.SOUTH);
add(new Button(“West”), BorderLayout.WEST);
add(new Button(“Center”), BorderLayout.CENTER);
Advanced Java Programming / © Shmulik London 2006 19
Combination of layouts
setLayout(new BorderLaout());
TextField display = new TextField();
add(display, BorderLayout.NORTH);
Panel buttonsPanel = new Panel();
buttonsPanel.setLayout(new GridLayout(4,4));
String[] labels = {“7”,”8”,”9”,”+”,”4”,”5”, ... };
for (int i=0; i<labels.length; i++) {
buttonsPanel.add(new Button(labels[i]));
}
Panel with
GridLayout
Frame with
BorderLayout
Advanced Java Programming / © Shmulik London 2006 20
Graphics
• Every component can serve as a graphical context
• In order to draw on a component, you override its paint method to define the drawing.
• You don’t call the paint method, it is called automatically by the windowing system whenever there is a need to display the component
• paint receives as parameter a Graphics object which has methods for drawing on the component
• Graphics is another example for the Strategy pattern
Advanced Java Programming / © Shmulik London 2006 21
Graphics
import java.awt.*;
// A frame that displays some graphics on itclass GraphicsExample extends Frame {
public void paint(Graphics painter) {painter.setColor(Color.black);painter.drawLine(20,20,400,300);painter.setColor(Color.blue);painter.drawRect(50,50,150,100);painter.setColor(Color.yellow);painter.fillOval(250,100,80,80);painter.setColor(Color.green);painter.fillRect(100,200,150,100);
}}
Advanced Java Programming / © Shmulik London 2006 22
Graphics
Advanced Java Programming / © Shmulik London 2006 23
Graphics
• In order to display a drawing that is not fixed, the implementation of paint should depend on the state of the object
• Whenever the state changes, we need to call the repaint() method in order to refresh the display of the component.
• repaint() asks the windowing system to call the paint() method with the suitable graphics object.
• Actually, the windowing system calls the method update() which clear the display and then call the method paint().
Advanced Java Programming / © Shmulik London 2006 24
Graphics
/*** A figure of a LED*/
public class LEDFigure extends Component {
// The state of the LED on/offprivate boolean isOn;
/*** Draws this LED.*/public void paint(Graphics g) {
g.setColor(isOn ? Color.red.brighter() : Color.red.darker());
g.fillOval(0,0,getSize().width,getSize().height);g.setColor(Color.black);g.drawOval(0,0,getSize().width,getSize().height);
}
Advanced Java Programming / © Shmulik London 2006 25
Graphics
/*** Sets the state of the LED.*/
public void setOn(boolean state) {isOn = state;repaint();
}
/*** Returns the state of the LED.*/
public boolean isOn() {return isOn;
}}
Advanced Java Programming / © Shmulik London 2006 26
Graphics
setOn()
LED
Windowing
Systemupdate()
paint()
repaint()
Please
update my
display
clear display
paint
display
Graphics
Advanced Java Programming / © Shmulik London 2006 27
AWT event handling
• All components of the AWT are written as JavaBeans.
• You handle events fired by AWT components by registering listeners to the events they fire.
• The various events fired by AWT components and the interfaces of the corresponding listeners are defined in package java.awt.event
• You can find out which events are supported by a component by searching its API for addXXXListener() and removeXXXListener() pairs.
Advanced Java Programming / © Shmulik London 2006 28
AWT events
ActionEvent ActionListeneractionPerformed(ActionEvent)
TextEvent TextListenertextValueChanged(TextEvent)
MouseEvent MouseListenermouseClicked(MouseEvent)mouseEntered(MouseEvent)mouseExited(MouseEvent)mousePressed(MouseEvent)mouseReleased(MouseEvent)
MouseMotionListenermouseDragged(MouseEvent)mouseMoved(MouseEvent)
... ...
Advanced Java Programming / © Shmulik London 2006 29
ActionEvent
import java.awt.*;import java.awt.event.ActionEvent;
// A simple ActionListener that prints “clicked”// whenever it is notified for an ActionEventclass SimpleListener implements ActionListener {
/*** Called to notify this object that some* action occured.*/
public void actionPerformed(ActionEvent event) {System.out.println(“clicked”);
}}
Advanced Java Programming / © Shmulik London 2006 30
ActionEvent
// An example for listening for pressing of a butto nclass ListeningExample extends Frame {
public ListeningExample() {Button okButton = new Button(“OK”);add(okButton);pack();ActionListener listener =
new SimpleListener();okButton.addActionListener(listener);
}
public static void main(String[] args) {new ListeningExample().setVisible(true);
}}
Advanced Java Programming / © Shmulik London 2006 31
MouseEvent
import java.awt.*;import java.awt.event.*;
// A teasing game in which the user is encouraged// to catch a figure on the screen, but whenever// the mouse cursor gets near the figure it runs aw ayclass CatchMeGame extends Panel {
// The figure the user need to catchprivate Component figure;
// The distance beyond which the figure runs awayprivate static final int MINIMAL_DISTANCE = 50;
Advanced Java Programming / © Shmulik London 2006 32
MouseEvent
public CatchMeGame() {setLayout(null);figure = new Smily();// .. set location & dimension of figureadd(figure);addMouseListener(new RunAwayAdapter(figure);
}
public static void main(String[] args) {Frame f = new Frame(“Catch me!”);f.setSize(400,300);f.add(new CatchMeGate());f.setVisible(true);
}}
Advanced Java Programming / © Shmulik London 2006 33
MouseEvent
// An adapter that listen to the movements of the m ouse// and keeps the figure from being caughtclass RunAwayAdapter implements MouseMotionListener {
private Component figure;
public RunAwayAdapter(Component figure) {this.figure = figure;
}
public void mouseMoved(MouseEvent event) {runAway(event.getPoint());
}
public void mouseDragged(MouseEvent event) {runAway(event.getPoint());
}
Advanced Java Programming / © Shmulik London 2006 34
MouseEvent
private void runAway(Point mouse) {// ... compute the center of the figure xm,ym
// if mouse if far away stay in placeif (Math.abs(mouse.x-xm)>MINIMAL_DISTANCE ||
Math.abs(mouse.y-ym)>MINIMAL_DISTANCE) {return;
}
// .. decide for the direction of the movement
figure.setLocation(figure.getLocation().x+dx,figure.getLocation().y+dy);
repaint();}
}
Advanced Java Programming / © Shmulik London 2006 35
Adapters (the need)
import java.awt.*;import java.awt.event.*;
/*** A panel that lets the user draw freehand lines*/
public class DrawingPanel extends Panel {
// The points composing the path drawn by the userjava.util.List path;
public DrawingPanel() {addMouseListener(new StartDrawingAdapter(this));addMouseMotionListener(new DrawingAdapter(this));
}
Advanced Java Programming / © Shmulik London 2006 36
Adapters (the need)
/*** Paints this component*/
public void paint(Graphics g) {if (path==null) {
return;}for (int i=0; i<path.size()-1; i++) {
Point p1 = (Point)path.get(i);Point p2 = (Point)path.get(i+1);g.drawLine(p1.x, p1.y, p2.x, p2.y);
}repaint();
}
}
Advanced Java Programming / © Shmulik London 2006 37
Adapters (the need)
// Cleans the path at the beginning of the draggingclass StartDrawingAdapter implements MouseListener() {
private DrawingPanel target;
public StartDrawingAdapter(DrawingPanel target) {this.target = target;
}
public void mousePressed(MouseEvent e) {target.path = new ArrayList();
}
public void mouseReleased(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}...
Advanced Java Programming / © Shmulik London 2006 38
Adapters (the need)
// Adds the points to the path during the draggingclass DrawingAdapter implements MouseMotionListener {
private DrawingPanel target;
public DrawingAdapter(DrawingPanel target) {this.target = target;
}
public void mouseDragged(MouseEvent e) {target.path.add (e.getPoint());target.repaint();
}
public void mouseMoved(MouseEvent e) {}
}
Advanced Java Programming / © Shmulik London 2006 39
Adapters
• In the previous example the listener classes need to implement all the method defined in the interface even though they are interested only in implementing part of them.
• This is a bit elaborating
• To avoid this, the API include for every listener interface that defines more than a single method, an adapter class that implement the interface in a trivial way.
Advanced Java Programming / © Shmulik London 2006 40
Adapters
package java.awt.event;
/*** Adapter for MouseEvents ...*/
public abstract class MouseAdapterimplements MouseListener{
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
// ... mouseExited, mouseClicked as well}
Advanced Java Programming / © Shmulik London 2006 41
Adapters
// Cleans the path at the beginning of the draggingclass StartDrawingAdapter extends MouseAdapter {
private DrawingPanel target;
public StartDrawingAdapter(DrawingPanel target) {this.target = target;
}
public void mousePressed(MouseEvent e) {target.path = new ArrayList();
}}
Advanced Java Programming / © Shmulik London 2006 42
Inner classes
• In both previous examples the main classes created adapters to act upon itself
• This is a common case
• This adds to the complexity of the code:
– the main object has to pass a reference of itself to the adapters
– the adapters has to define a field and a suitable constructor to record the target object
– in the adapter we make frequent use of the target reference
Advanced Java Programming / © Shmulik London 2006 43
Inner classes
• To make the code more compact (less error prone) Java let you define inner classes
• Inner classes are classes defined inside the body of another class.
• Instance of inner-classes has automatic access to fields defined in the enclosing class, with no need to denote the reference to the enclosing object.
• There are several other details of inner-classes that we skip. You can read about them in the documentation of the JDK.
Advanced Java Programming / © Shmulik London 2006 44
Inner classes
import java.awt.*;import java.awt.event.*;
/*** A panel that lets the user draw freehand lines*/
public class DrawingPanel extends Panel {
// The points composing the pathjava.util.List path;
public DrawingPanel() {addMouseListener(
new StartDrawingAdapter(this));addMouseMotionListener(
new DrawingAdapter(this));}
Advanced Java Programming / © Shmulik London 2006 45
Inner classes
/*** Paints this component*/
public void paint(Graphics g) {if (path==null) {
return;}for (int i=0; i<path.size()-1; i++) {
Point p1 = (Point)path.elementAt(i);Point p2 = (Point)path.elementAt(i+1);g.drawLine(p1.x, p1.y, p2.x, p2.y);
}repaint();
}
Advanced Java Programming / © Shmulik London 2006 46
Inner classes
// Cleans the path at the beginning of the dragclass StartDrawingAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {path = new java.util.ArrayList();
}}
// Adds the points to the path during the dragclass DrawingAdapter extends MouseAdapter {
public void mouseDragged(MouseEvent e) {path.add(e.getPoint());repaint();
}}
}
Advanced Java Programming / © Shmulik London 2006 47
Anonymous classes
• If an inner class is needed only for a single useand its constructor gets no parametersyou can define it as an anonymous class
• Anonymous class are defined in the place in the code were they are needed, and you immediately create an instance of the anonymous class
• Use anonymous classes with care - they should be used only where the code of the class is very compact 1-3 lines.
Advanced Java Programming / © Shmulik London 2006 48
Anonymous classes
// .. as beforepublic class DrawingPanel extends Panel {
// ..
public DrawingPanel() {addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {path = new ArrayList();
}});addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {path.add(e.getPoint());repaint();
}});
}