mt311 (oct 2006) java application development

62
MT311 (Oct 2006) Java Application Developmen t Tutorial 2 Graphical User Interface

Upload: deanna

Post on 13-Feb-2016

60 views

Category:

Documents


5 download

DESCRIPTION

MT311 (Oct 2006) Java Application Development. Tutorial 2 Graphical User Interface. Tutor Information. Edmund Chiu (Group 1) Email: [email protected] OR [email protected] Please begin your email subject with [MT311] Webpage: http://learn.ouhk.edu.hk/~t439934. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: MT311 (Oct 2006) Java Application Development

MT311 (Oct 2006)Java Application Development

Tutorial 2Graphical User Interface

Page 2: MT311 (Oct 2006) Java Application Development

Tutor Information

Edmund Chiu (Group 1) Email: [email protected] OR

[email protected] Please begin your email subject with [MT311] Webpage: http://learn.ouhk.edu.hk/~t439934

Page 3: MT311 (Oct 2006) Java Application Development

PART IGUI Components

ContainersComponentsEvents and ListenersLayout Managers

Page 4: MT311 (Oct 2006) Java Application Development

Java GUI Framework

In early day, Java GUI are supported by Abstract Window Toolkit (AWT)

– Based on native widget in different platform– Buggy and not really portable

Java Foundation Class (JFC) was introduced in Java 1.1

– AWT was replaced by Swing (javax.swing.*)– Other package in JFC provides 2D advanced graphics, plugga

ble look and feel, drag and drop and other facilities

Page 5: MT311 (Oct 2006) Java Application Development

Containers

Originated from AWT Logical grouping of other containers and

components Top level containers appear as windows and

define your application areas– With title bar, system buttons and frame– Can be resized, moved and closed

Page 6: MT311 (Oct 2006) Java Application Development

JFrame

Basic windowing supports such as title, positioning and resizing

Steps to use JFrame1. Create the frame with a particular title

JFrame frame = new JFrame(“Hello World”);2. Add containers and/or controls to the frame

JButton button = new JButton(“Say Hello”);frame.getContentPane().add(button);

3. Arrange the controlsframe.pack()

4. Make the frame visibleframe.setVisible(true);

Page 7: MT311 (Oct 2006) Java Application Development

Sample Code (JFrame)

import javax.swing.*;public class FrameDemo {

public static void main (String[] args) {

JFrame frame = new JFrame (“Demo”);

frame.setSize(200,200); frame.setVisible(true);}

}

Page 8: MT311 (Oct 2006) Java Application Development

Other Issues on JFrame

The close button only closes your JFrame, but not ends your application

– Solution: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

You can set the initial size of your JFrame using setSize(int width, int height)

You should explore the way to use other methods in JFrame by using the API specification

Page 9: MT311 (Oct 2006) Java Application Development

JDialog

Simple window used for short-lived interactions such as – Prompting user for responses– Informing user of certain events

To create a dialogJDialog dlg = new JDialog(owner, title, modality);– Modal dialog is used if you need user’s response before proceed

ing– Non-modal dialog is used to present information that is safe to b

e ignored JOptionPane is used for generating common use standar

d dialogs

Page 10: MT311 (Oct 2006) Java Application Development

JOptionPane’s Message Dialog

Generate using:JOptionPane.showMessageDialog(null,

“I’m the light of the world.”, “Hello World”, JOptionPane.INFORMATION_MESSAGE);

Page 11: MT311 (Oct 2006) Java Application Development

JApplet

Applets are lightweight applications that can be embedded in a browser– Restricted from accessing and/or using local system

resources No main methods

– init() method do the initialization and kick off job

Page 12: MT311 (Oct 2006) Java Application Development

Sample Applet

import javax.swing.*;public class AppletDemo extends JApplet {

public void init() {JButton button = new JButton("Say Hello");

getContentPane().add(button); }}

Page 13: MT311 (Oct 2006) Java Application Development

Intermediate Containers

Intermediate containers are components that can contain other components

– Cannot stand alone– Can be nested – containers can be placed inside a container

JPanel is the most common intermeidate containers– JPanel does not have a visual realization – In general, it is used to group other controls to create

More logical organization Easier positioning and resizing

Page 14: MT311 (Oct 2006) Java Application Development

JScrollPane

A JScrollPane provides a scrollable view of a component– Horizontal and vertical scrollbars are given to move

the component inside when it is larger than the physical area on the screen

Page 15: MT311 (Oct 2006) Java Application Development

JSplitPane

Used to split an area into two distinct and independent partitions

– splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,listScrollPane, pictureScrollPane);

Page 16: MT311 (Oct 2006) Java Application Development

JTabbedPane

You can have several components (usually panels) share the same space.

– By selecting the individual tab, one of the components can be shown at a time

How to use:1. Create a JTabbedPane2. Add components to the JTabbedPane

E.g.: tabbedPane.addTab("Tab 1", panel1);

Page 17: MT311 (Oct 2006) Java Application Development

JToolBar

JToolBar is a container that groups several components (usually buttons with icons) into a row or column

Often, tool bars provide easy access to functionality that is also in menus

Page 18: MT311 (Oct 2006) Java Application Development

Controls (JComponents)

Controls differ from containers in that they actually do something on an interface

Some common controls:– JLabel – display read-only text and icons support HTML formatting– Buttons – includes JButton, JRadioButton, and JCheckBox– Text Components – includes JTextField (single line text input) and

JTextArea (multi-line editing)– Selection – JComboBox (drop-down list) and JList – Menus – JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, a

nd JRadioButtonMenuItem– Others – JSlider, JSpinner, Progress bars and etc.

Page 19: MT311 (Oct 2006) Java Application Development

JComponent Methods

Common methods for the components– get/setText– setEnabled– isSelected– Millions of methods are supported by different components. You sh

ould review Java API specification and the respective online Java Tutorial to understand how to use them

One last point on JRadioButton– They should be grouped into ButtonGroup in order to make only on

e radio button in the group being selected– However ButtonGroup is NOT a component and cannot be added

to the container

Page 20: MT311 (Oct 2006) Java Application Development

Common Controls

There are stillmany other!!

Page 21: MT311 (Oct 2006) Java Application Development

More Complex Components

Page 22: MT311 (Oct 2006) Java Application Development

Building a Swing Interface

Step 1 – choose a top-level container– JFrame? JApplet?

Step 2 – choose an intermediate container (if necessary)

Step 3 – place your components (labels, buttons and etc.) onto the intermediate container(s)

Step 4 – add your intermediate container(s) to the top-level container

Step 5 – arrange the frame and show the window

Page 23: MT311 (Oct 2006) Java Application Development

Sample Program in Building Swing GUI

import javax.swing.*; // import the Swing componentspublic class HelloWorldSwing { public static void main(String[] args) { JFrame frame = new JFrame("Hello World"); JPanel pane = new JPanel(); JLabel label = new JLabel("Hello World"); JButton button = new JButton("Say Hello"); pane.add(label); pane.add(button); frame.getContentPane().add(pane); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }}

Page 24: MT311 (Oct 2006) Java Application Development

Event-Driven Programs

In conventional procedural programs– Flow of control depends on input data only, deal with one input

channel at a time (single-threaded)– Example: program wait for keyboard input and ignore other

input until the first input is received– Disadvantage – most events are random in no particular order

Event-driven program deals with any event when it arrives

– User actions generate events– If you want to react to an event, you attach an event listener– When an event fires (happens), the event handler is invoked

Page 25: MT311 (Oct 2006) Java Application Development

Events

An event is generated whenever there is a change to a component– Component resized component event– Mouse clicked mouse event

A component can generate multiple event– A button “clicked” maybe mouse, maybe keyboar

d– We should handle semantic events (button clicked –

ActionEvent) instead of low-level events

Page 26: MT311 (Oct 2006) Java Application Development

Event Listeners

To react to a particular event, you need an event listener (interface)

As there are many types of event, each should have their own listener interface

Components have specific addXXXListener methods to attach event listeners to them

Multiple event listeners may be registered to the same components

The same event listener may be registered to multiple components

Page 27: MT311 (Oct 2006) Java Application Development

Events and Event Listeners ActionEvent ComponentEvent ContainerEvent FocusEvent InputEvent (Key/Mouse) InputMethodEvent InvocationEvent (run method) ItemEvent KeyEvent MouseEvent MouseWheelEvent PaintEvent TextEvent WindowEvent

ActionListener ComponentListener ContainerListener FocusListener InputMethodListener ItemListener KeyListener MouseListener MouseMotionListener MouseWheelListener TextListener WindowFocusListener WindowListener WindowStateListener

Page 28: MT311 (Oct 2006) Java Application Development

Event Information

To grab more information from an event to be handled, all event listener methods have a parameter giving the information regarding the specific event– public void actionPerformed (ActionEvent e) {…}

The event object can provide information like– Event source– Event type

Page 29: MT311 (Oct 2006) Java Application Development

Extending HelloWorldSwing Example

Add a class MyActionListener– public class MyActionListener implements ActionListener {

public void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(…);

}}

Remember to register your button the action listener – MyActionListener myListener = new MyActionListener();

Button.addActionListener(myListener);

Page 30: MT311 (Oct 2006) Java Application Development

Event Adapters

As Listeners are interfaces, you are required to implement all listener methods even you are not using one of them.

– Empty methods can be used for those listener methods you are not required in the program

Java provides Adapter classes for every Listener, with all methods empty

– E.g., MouseListener has five methods: mousePressed, mouseReleased, mouseEntered, mouseExited and mouseClicked

– User can use MouseAdapter and override only the method(s) they are care about.

Page 31: MT311 (Oct 2006) Java Application Development

Listener/Adapter Methods

Component Listener/Adapter– componentHidden, componentMoved, componentResized, co

mponentShown Container Listener/Adapter

– componentAdded, componentRemoved Focus Listener/Adapter

– focusGained, focusLost Key Listener/Adapter

– keyPressed, keyReleased, keyTyped

Page 32: MT311 (Oct 2006) Java Application Development

Listener/Adapter Methods (cont’d)

Mouse Listener/Adapter– mouseClicked, mouseEntered, mouseExited, mousePressed,

mouseReleased Mouse Motion Listener/Adapter

– mouseDragged, moseMoved Mouse Input Listener/Adapter

– mouse listener + mouse motion listener Window Listener/Adapter

– windowActivted, windowClosed, windowClosing, windowDeactivated, windowDeiconified, windowIconified, windowOpened

Page 33: MT311 (Oct 2006) Java Application Development

Writing Event Listeners

Many methods to write a event listener– Create a new ActionListener class (like the original example)

Not good because creating a new class is rather heavy-handed

– Making the HelloWorldSwing class implements ActionListener and put the method inside the HelloWorldSwing classMost casual programmers do so, but work in simple cases only. When the program becomes complex, we do not know which method is for the Listener and which is for the application

Page 34: MT311 (Oct 2006) Java Application Development

Writing Event Listeners (cont’d)

– Use inner class: define the listener class inside the application programEncapsulate the listener inside the class

– Use anonymous class: we do not even need to have a class – the listener is only for the button we are handling

– Inner class and anonymous class may make elegant and efficient code, but at the same time, may also make the code incomprehensible

Page 35: MT311 (Oct 2006) Java Application Development

Direct Implementing ActionListener

public class HelloWorldSwing implements ActionListener {::public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(…);}

}

Page 36: MT311 (Oct 2006) Java Application Development

Anonymous Event Listener

button.addActionListener (new ActionListener() { public void actionPerformed (ActionEvent e) {

JOptionPane.showMessageDialog(…); }}

);

Page 37: MT311 (Oct 2006) Java Application Development

Layout

The way of arranging components on a container is layout– Overall placement and size

Layout manager determine the relative position of the components.

– Java can still use absolute positioning (by setting layout manager to null)

– Layout managers are used because Java programs may appear in different platform which may have a different font, different screen size and etc. Flexible layouts are needed.

Most GUI use flow layout as default– Default as BorderLayout: JApplet, JFrame and Dialog– Default as FlowLayout: Panel, Applet and JPanel

Page 38: MT311 (Oct 2006) Java Application Development

Common Layout Managers

FlowLayout – arranges components from left to right

GridLayout – displays components in a rectangular grid– E.g., container.setLayout(new GridLayout(2,3));

means 2 rows and 3 cols, components are added from left to right, then top to bottom.

BorderLayout – divides the container into regions – programmers specifies where to place their components– The regions are PAGE_START (NORTH), PAGE_END (SOUTH), LI

NE_START (WEST), LINE_END (EAST) and CENTER

Page 39: MT311 (Oct 2006) Java Application Development

Border Layout Exampleimport java.awt.*;import javax.swing.*;public class BorderLayoutDemo { public static void main(String[] args) { JFrame frame = new JFrame("BorderLayoutDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container pane = frame.getContentPane(); pane.add(new JButton("PAGE_START"), BorderLayout.PAGE_START); pane.add(new JButton("LINE_START"), BorderLayout.LINE_START); pane.add(new JButton("CENTER"), BorderLayout.CENTER); pane.add(new JButton("LINE_END"), BorderLayout.LINE_END); pane.add(new JButton("PAGE_END"), BorderLayout.PAGE_END); frame.pack(); frame.setVisible(true); }}

Page 40: MT311 (Oct 2006) Java Application Development

Component Size

By default, each component has a natural size– E.g., a button is just as tall and wide enough to fit the button la

bel We can override the default by setting the preferred siz

e– E.g., button.setPerferredSize(new Dimension(50, 200));– You may set the maximum/minimum size of the component als

o, but the methods are not supported by all layout managers

Page 41: MT311 (Oct 2006) Java Application Development

Component Size and Layout Manager

In Border Layout– Components in N and S will have natural height, but extend to full

width– Components in E and W will have natural width but full height– Center is region is greedy, it occupies all area left by N, E, S, W

In Grid Layout– Each component occupies full width and height of its own grid

In Flow Layout– All components are in natural size

Always use JPanel to group your components to make your layout flexible

Page 42: MT311 (Oct 2006) Java Application Development

Other Layout Manager

Box Layout– Good for single row / single column layout

Spring Layout– Most suitable for form – multiple rows and columns i

n varying width and height GridBag Layout

– Most powerful layout – grid based, but a component can span multiple rows and/or columns

Page 43: MT311 (Oct 2006) Java Application Development

PART IIJava Graphics

Page 44: MT311 (Oct 2006) Java Application Development

Graphics

You can paint anything onto a graphical context– E.g, A JButton knows how to draw itself, and you can even mak

e it to have an image on itself All components have a graphics context

– Graphics g = component.getGraphics(); // not the usual way We usually get the graphics object through the paint met

hod – void paint (Graphics g)– Paint method is called whenever the component needs repaint– Custom drawing is made by overriding the component’s paint m

ethod

Page 45: MT311 (Oct 2006) Java Application Development

Coordinate System in Java

Upper-left corner of the GUI component (a window or an applet) is (0, 0)

x-coordinates increases from left to right y-coordinates increases from top to bottom coordinates are measured in the number of

pixels

Page 46: MT311 (Oct 2006) Java Application Development

Drawing Lines and Shapes

drawLine(int x1, int y1, int x2, int y2)– Draws a line between the points (x1, y1) and (x2, y2) in this gr

aphics context's coordinate system. drawRect(int x, int y, int w, int h)

– Draws a rectangle with its top-left corner at (x, y), and its width as w and its height as h

drawOval(int x, int y, int w, int h)– Draws a circle or an ellipse that fits within the rectangle with to

p-left angle at (x, y), the width of the rectangle as w, and the height as h.

Page 47: MT311 (Oct 2006) Java Application Development

Drawing Lines and Shapes (cont’d)

drawPolygon(int[] xPoints, int[] yPoints, int nPoints)– Draws a closed Polygon which vertices are specified by the array

s of x- and y- coordinates drawArc(int x, int y, int width, int height, int startAngle, int

arcAngle)– Draws the arc which:– begins at startAngle and extends for arcAngle degrees

Angles are interpreted such that 0 degrees is at the 3 o'clock position. A positive value indicates a counter-clockwise rotation.

– (x, y) is the coordinates of the top-left corner of the rectangle embedding the arc. The size of such rectangle is specified by the width and height arguments.

Page 48: MT311 (Oct 2006) Java Application Development

Filling Shapes

The following methods draw a filled shape (filled with current Color)

– fillRect(int x, int y, int w, int h)– fillOval(int x, int y, int w, int h)– fillPolygon(int[] xPoints, int[] yPoints, int nPoints)– fillArc(int x, int y, int width, int height, int startAngle, int arcAngl

e) There are still many other shapes Java can draw

– draw3DRect, drawRoundRect, clearRect and etc.

Page 49: MT311 (Oct 2006) Java Application Development

Color Class

Color class contains color constants and methods– Each color is created from RGB (Red-Green-Blue) value

Color constructors:– public Color (int r, int g, int b)

Color components can be retrieved using methods getRed(), getBlue() and getGreen()

Common color can be retrieved using Color constants– Examples: Color.red, Color.orange, Color.yellow, Color.green

To change the color used in a Graphics object, call setColor method

– Example: g.setColor(Color.red);

Page 50: MT311 (Oct 2006) Java Application Development

Sample Applet of Drawing Lines and Shapes

import javax.swing.JApplet;import java.awt.*;public class DrawLineDemo extends JApplet { public void init() { setBackground(

new Color(0xcc, 0xcc, 0xcc)); } public void paint(Graphics g) { g.setColor(Color.red); g.drawLine(0, 0, 100, 100); g.setColor(Color.green); g.drawLine(250, 250, 120, 13);

g.setColor(Color.blue); g.fillRect(100, 100, 100, 80); g.setColor(Color.orange); g.drawOval(30, 30, 200, 200); int x[] = { 19, 234, 9, 192, 62}; int y[] = { 35, 135, 241, 141, 71}; g.setColor(Color.cyan); g.fillPolygon(x, y, 5); }}

Page 51: MT311 (Oct 2006) Java Application Development

Output of DrawLineDemo Applet

Page 52: MT311 (Oct 2006) Java Application Development

Graphics 2D

Graphics object provides primary drawing functions only

Graphics2D object provides more advanced features such as

– Solid, dotted and patterned lines of any width– Gradient paint, image filling– Shape rotating, stretching and squashing

You can safely upcast a Graphics object to Graphics2D

Page 53: MT311 (Oct 2006) Java Application Development

Sample Code of Graphics2D Applet

(Only paint method is shown here)public void paint(Graphics g) { // cast Graphics to Graphics2D Graphics2D g2 = (Graphics2D) g; Dimension d = getSize(); // fill Ellipse2D.Double g2.setPaint(new GradientPaint(0, 0, Color.red, d.width, d.height, Color.white)); g2.fill(new Ellipse2D.Double(0, 0, d.width, d.height)); }

Page 54: MT311 (Oct 2006) Java Application Development

Output of Graphics2D Applet

Page 55: MT311 (Oct 2006) Java Application Development

Draw a String

Method drawString(String s, int x, int y) can display a string s with the current font at the position of (x, y) (baseline of the first character)

Current font can be set and retrieved using the methods – void setFont(Font f) – String getFont()

Page 56: MT311 (Oct 2006) Java Application Development

Using a Font

Font class contains constants and methods for manipulating fonts

Font Constructor: – public Font(String name, int style, int size)

name = name of the font style = font style

use font style constants: Font.PLAIN, Font.BOLD and Font.ITALIC (Font.BOLD | Font.ITALIC to apply both bold and italic)

size are measured in points (1 point = 1/72 inch) Java 2D graphics has anti-aliasing capability to make te

xt look smoother

Page 57: MT311 (Oct 2006) Java Application Development

Font Information

A list of available fonts can be retrieved through method getFontList in the AWT Toolkit class:

– String fontList[] =ToolKit.getDefaultToolKit().getFontList();

FontMetrics class defines methods to obtain font metrics such as height, ascent, descent and etc.

– FontMetrics object can be retrieved from a Font object using getFontMetrics()

– Using getStringBounds method in FontMetrics can know the exact length of a string shown in the screen

Page 58: MT311 (Oct 2006) Java Application Development

Drawing String Example

public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.blue); g2.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 18)); g2.drawString("Changing your font is FUNNY.", 50, 50); }

Page 59: MT311 (Oct 2006) Java Application Development

Drawing an Image

To display image file, you use drawImage– boolean drawImage (Image img, int x, int y, ImageObserver o)

draws image at x, y without scaling– boolean drawImage (Image img, int x, int y, int width, int height,

ImageObserver o) draws image at x, y to a specific width and height

To get image from the file– Image img = Toolkit.getDefaultToolkit().getImage(<file>);

ImageObserver is the object which will be repainted when the image needs refresh (this)

Page 60: MT311 (Oct 2006) Java Application Development

Image Drawing Sample Code

import javax.swing.JApplet;import java.awt.*;public class DrawImageDemo extends JApplet { Image img; public void init() { img = getImage(getDocumentBase(), "images/demo.gif"); setBackground(Color.white); } public void paint(Graphics g) { g.drawImage(img, 0, 0, getWidth(), getHeight(), this); }}

Page 61: MT311 (Oct 2006) Java Application Development

Pluggable Look and Feel

UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");

Page 62: MT311 (Oct 2006) Java Application Development

Other Advanced Features

Drag and Drop – Java’s Data Transfer package (in Swing) supports

Drag and Drop of GUI components and other objects

Design Pattern– MVC– Observer/Observable pattern