30
1 Java Lectures User interfaces and Swing Overview, applets, drawing, action listening, layout managers. APIs: java.awt.*, javax.swing.*, classes names start with a J.

User interfaces and Swing - n.saunier.free.frn.saunier.free.fr/saunier/teaching/java/JavaSwingLecture.pdf · Java Lectures 1 User interfaces and Swing Overview, – applets, drawing,

Embed Size (px)

Citation preview

1Java Lectures

User interfaces and Swing

● Overview,– applets, drawing, action listening, layout

managers.

● APIs:– java.awt.*,

– javax.swing.*, classes names start with a J.

2Java Lectures

Applets

public class Simple extends Applet {public void init() { . . . }public void start() { . . . }public void stop() { . . . }public void destroy() { . . . }

}

init() to initialize the applet each time it's loaded (or reloaded). start() to start the applet's execution, such as when the applet's loaded or when the user revisits a page that contains the applet. stop() to stop the applet's execution, such as when the user leaves the applet's page or quits the browser. destroy() to perform a final cleanup in preparation for unloading.

3Java Lectures

Run an applet

<HTML><BODY><APPLET CODE=SimpleApplet.class WIDTH=200 HEIGHT=100></APPLET></BODY></HTML>

appletviewer simpleApplet.html

file simpleApplet.html

4Java Lectures

Applets and standalone applications

● The user interface is attached to a panel object nested– for applets, in a top-level browser,

– for a swing application: in a top-level frame object.

● A frame object is a top-level window that provides a title, banner, and methods to manage the appearance and behavior of the window.

5Java Lectures

A simple window

● upper left corner, coordinates (200, 100) from the upper left corner of the screen.

● width: 300 pixels; height: 350 pixels.

the whole is an instance of javax.swing.JFrame.

container of the window

6Java Lectures

Code of the simple window

import javax.swing.JFrame;

class Window { public static void main(String[] args) {

JFrame cadre = new JFrame("Empty");cadre.setSize(300, 350);cadre.setLocation(200, 100);cadre.show();

}}

7Java Lectures

A small application

JFrame

JPanel

JPanel

JPanel

JButton

8Java Lectures

import javax.swing.*;import java.awt.event.*;import java.awt.*;

class Container extends JPanel implements ActionListener { JButton show = new JButton("show");JButton erase = new JButton("erase");JPanel board = new JPanel();

Container() {

setLayout(new BorderLayout(5, 5));

JPanel theButtons = new Jpanel(); // for the buttonstheButtons.add(show);theButtons.add(erase);add(theButtons, BorderLayout.NORTH);

board.setPreferredSize(new Dimension(200, 150));board.setBackground(Color.white);add(board, BorderLayout.CENTER);

show.addActionListener(this);erase.addActionListener(this);

}...

9Java Lectures

public void actionPerformed(ActionEvent e) {Object source = e.getSource();

if (source == show) {Graphics g = board.getGraphics();

g.setColor(Color.red);g.drawOval(50,20,100,100);g.dispose();

} else if (source == erase) {board.repaint();

}}

public static void main(String[] argv) {

JFrame myFrame = new JFrame();myFrame.setContentPane(new Container());myFrame.pack();myFrame.show(); // or myFrame.setVisible(true);

}}

10Java Lectures

Drawing

● Every JComponent object contains:

– a background and a foreground color,● public Color getForeground();

● public void setForeground(Color c);

– a font,● public Font getFont();

● public void setFont(Font f);

– a method, ● public Graphics getGraphics();

11Java Lectures

The Graphics class

● Magic pencil for a graphical component.● It holds a graphic context:

– the painted component,

– a color for drawing: setColor(Color c);

– a font: setFont(Font f);

– a "clipping" rectangle (render area),– draw methods,

● drawRect(), drawLine()...

12Java Lectures

Paint

● repaint() calls the paint() method, which calls the method paintComponent(),

– then a method to repaint the borders,

– then the paint() methods of the sub-components, down the containment hierarchy.

13Java Lectures

Button: Action listening

● The interface ActionListener contains only one method declaration– public void actionPerformed(ActionEvent e);

● How button-generated actions are passed to the actionPerformed method ?

– trace.addActionListener(delegate);

– the delegate object must implement ActionListener, and thus has a method actionPerformed.

14Java Lectures

Action listening

– means: when the button show is clicked, the method actionPerformed of delegate is invoked.

– an ActionEvent object is created when the button is clicked, and passed to actionPerformed.

– Event handling in the actionPerformed method:

● for example, drawing.

15Java Lectures

Events

● Click a button,● Chose an item in a menu,● Push the button of the mouse/move the

mouse while the pointer is on a component,● Type "return" when working in a text area,● Close the window of the application,● Press any key.● ...

16Java Lectures

Action listening and event handling

● Events are "perceived" by the computer– passed to the Java program, treating the event,

according to the type of event and the concerned component.

– ActionEvent objects are created, representing the event.

● Listeners are objects which treat some kind of events, implementing the right interface.– they are linked to a certain source (component),– they have methods to handle the events.

17Java Lectures

Other ActionListeners

● Many...● An adapter class implements empty versions

of all its interface's methods.– use inner classes.

Source

listener1

listener2

listener3

18Java Lectures

The event-dispatching thread

● It does event handling and the different painting operations on the screen,

● It treats everything sequentially: while an event is treated, the UI is suspended.

19Java Lectures

Another example: Mouse clicks

20Java Lectures

The MouseListener interface

● This listener allows to treat 5 types of events,– public void mousePressed(MouseEvent evt);

– public void mouseReleased(MouseEvent evt);

– public void mouseEntered(MouseEvent evt);

– public void mouseExited(MouseEvent evt);

– public void mouseClicked(MouseEvent evt);

21Java Lectures

A class for the circles

class GraphicCircle {int x,y, radius;

GraphicCircle(int radius, int x, int y) {this.radius = radius;this.x = x;this.y = y;

} public void draw(Graphics g) {g.fillOval(x - radius, y - radius,

2*radius, 2*radius);}

}

22Java Lectures

class TestClicks extends JPanel implements MouseListener {Vector memory = new Vector();

TestClicks() {setPreferredSize(new Dimension(250, 250));addMouseListener(this);

}

public void mouseClicked(MouseEvent evt) {memory.add(new GraphicCircle(15, evt.getX(),

evt.getY()));repaint();

}

public void mousePressed(MouseEvent evt) {}public void mouseReleased(MouseEvent evt) {}public void mouseEntered(MouseEvent evt) {}public void mouseExited(MouseEvent evt) {} ...

23Java Lectures

public void paintComponent(Graphics g) {super.paintComponent(g);for (int i = 0; i < memory.size(); i++)((GraphicCircle)memory.get(i)).draw(g);

}

public static void main(String[] args) {JFrame frame = new JFrame();frame.setContentPane(new TestClicks());frame.setLocation(50, 50);frame.pack();frame.setVisible(true);

}}

24Java Lectures

Layout managers

● java.awt.FlowLayout (default for JPanel): from left to right, starting new rows if necessary.

25Java Lectures

Layout managers (2)

● java.awt.BorderLayout (default for content pane): five areas available to hold components, north, south, east, west, and center. All extra space is placed in the center area.

● javax.swing.BoxLayout: puts components in a single row or column. It respects the components' requested maximum sizes, and also lets you align components.

26Java Lectures

Layout managers (3)

● javax.swing.CardLayout: implements an area that contains different components at different times.

● javax.swing.GridLayout: displays components in a grid.

● javax.swing.GridBagLayout: aligns components by placing them within a grid of cells, allowing some components to span more than one cell.

27Java Lectures

Some design solution

● Main advice: separate the user interface from the application. 2 classes,– the user interface,

– the application, implementing the ActionListener.

28Java Lectures

class Delegate implements MouseListener {Jpanel panel;

Delegate(JPanel _panel) {this.panel = _panel;

}

public void mouseClicked(MouseEvent evt) {panel.addCircle(new GraphicCircle(15, evt.getX(),

evt.getY()));repaint();

}

public void mousePressed(MouseEvent evt) {}public void mouseReleased(MouseEvent evt) {}public void mouseEntered(MouseEvent evt) {}public void mouseExited(MouseEvent evt) {}

}

29Java Lectures

class TestClicks extends JPanel {Vector memory = new Vector();

TestClicks() {setPreferredSize(new Dimension(250, 250));addMouseListener(new Delegate(this));

}

public void addCircle(GraphicCircle c) {memory.add(c);

}

public void paintComponent(Graphics g) {super.paintComponent(g);for (int i = 0; i < memory.size(); i++)((GraphicCircle)memory.get(i)).draw(g);

} ...

30Java Lectures

public static void main(String[] args) {JFrame frame = new JFrame();frame.setContentPane(new TestClicks());frame.setLocation(50, 50);frame.pack();frame.setVisible(true);

}}