Docsity

Java GUI Development: An Overview of Swing and AWT, Papers of Computer Science

Toggle sidebar
bg1
Introduction
to GUIs
(Graphical User
Interfaces)
Lecture 18
CS211 โ€“ Summer 2008
2
Interactive Programs
yโ€œClassicโ€ view of computer
programs: transform inputs to
outputs, stop
yEvent-driven programs:
interactive, long-running
๎šƒServers interact with clients
๎šƒApplications interact with
user(s)
user user
program
input
events
output
events
input
output
3
GUI Motivation
yInteracting with a program
๎šƒProgram-Driven
๎šŠStatements execute in sequential, predetermined order
๎šŠUse keyboard or file I/O, but program determines when that happens
๎šŠUsually single-threaded
๎šƒEvent-Driven
๎šŠProgram waits for user input to activate certain statements
๎šŠTypically uses a GUI (Graphical User Interface)
๎šŠOften multi-threaded
yDesign...Which to pick?
๎šƒProgram called by another program?
๎šƒProgram used at command line?
๎šƒProgram interacts often with user?
๎šƒProgram used in window environment?
yHow does Java do GUIs? 4
Java Support for Building GUIs
yJava Foundation Classes
๎šƒClasses for building GUIs
๎šƒMajor components
๎šŠawt and swing
๎šŠPluggable look-and-feel support
๎šŠAccessibility API
๎šŠJava 2D API
๎šŠDrag-and-drop Support
๎šŠInternationalization
yOur main focus: Swing
๎šƒBuilding blocks of GUIs
๎šŠWindows & components
๎šŠUser interactions
๎šƒBuilt upon the AWT (Abstract
Window Toolkit)
๎šŠJava event model
yJavaโ€™s support for cross-platform GUIs is one of its main selling
points
5
Java Foundation Classes
yPluggable Look-and-Feel Support
๎šƒControls look-and-feel for particular windowi ng environment
๎šƒE.g., Java, Windows, Motif, Mac
yAccessibility API
๎šƒSupports assistive technologies such as screen readers and Bra ille
yJava 2D
๎šƒDrawing
๎šƒIncludes rectangles, lines, circles, images, ...
yDrag-and-drop
๎šƒSupport for drag and drop between Java application and a native
application
yInternationalization
๎šƒSupport for other languages
6
GUI Statics and GUI Dynamics
yStatics: whatโ€™s drawn on the screen
๎šƒComponents
๎šŠbuttons, labels, lists, sliders, menus, ...
๎šƒContainers: components that contain other components
๎šŠframes, panels, dialog boxes, ...
๎šƒLayout managers: control placement and sizing of components
yDynamics: user interactions
๎šƒEvents
๎šŠbutton-press, mouse-click, key-press, ...
๎šƒListeners: an object that responds to an event
๎šƒHelper classes
๎šŠGraphics, Color, Font, FontMetrics, Dimension, ...
pf3
pf4
pf5
pf8

Partial preview of the text

Download Java GUI Development: An Overview of Swing and AWT and more Papers Computer Science in PDF only on Docsity!

Introduction

to GUIs

(Graphical User

Interfaces)

Lecture 18 CS211 โ€“ Summer 2008

2

Interactive Programs

y โ€œClassicโ€ view of computer programs: transform inputs to outputs, stop

y Event-driven programs: interactive, long-running ยƒ Servers interact with clients ยƒ Applications interact with user(s)

user user

program

input events

output events

input

output

3

GUI Motivation

y Interacting with a program ยƒ Program-Driven ยŠ Statements execute in sequential, predetermined order ยŠ Use keyboard or file I/O, but program determines when that happens ยŠ Usually single-threaded ยƒ Event-Driven ยŠ Program waits for user input to activate certain statements ยŠ Typically uses a GUI (Graphical User Interface) ยŠ Often multi-threaded

y Design...Which to pick? ยƒ Program called by another program? ยƒ Program used at command line? ยƒ Program interacts often with user? ยƒ Program used in window environment?

y How does Java do GUIs? (^4)

Java Support for Building GUIs

y Java Foundation Classes ยƒ Classes for building GUIs ยƒ Major components ยŠ awt and swing ยŠ Pluggable look-and-feel support ยŠ Accessibility API ยŠ Java 2D API ยŠ Drag-and-drop Support ยŠ Internationalization

y Our main focus: Swing ยƒ Building blocks of GUIs ยŠ Windows & components ยŠ User interactions ยƒ Built upon the AWT (Abstract Window Toolkit) ยŠ Java event model

y Javaโ€™s support for cross-platform GUIs is one of its main selling points

Java Foundation Classes

y Pluggable Look-and-Feel Support ยƒ Controls look-and-feel for particular windowing environment ยƒ E.g., Java, Windows, Motif, Mac

y Accessibility API ยƒ Supports assistive technologies such as screen readers and Braille

y Java 2D ยƒ Drawing ยƒ Includes rectangles, lines, circles, images, ...

y Drag-and-drop ยƒ Support for drag and drop between Java application and a native application

y Internationalization ยƒ Support for other languages

GUI Statics and GUI Dynamics

y Statics: whatโ€™s drawn on the screen ยƒ Components ยŠ buttons, labels, lists, sliders, menus, ... ยƒ Containers: components that contain other components ยŠ frames, panels, dialog boxes, ... ยƒ Layout managers: control placement and sizing of components

y Dynamics: user interactions ยƒ Events ยŠ button-press, mouse-click, key-press, ... ยƒ Listeners: an object that responds to an event ยƒ Helper classes ยŠ Graphics, Color, Font, FontMetrics, Dimension, ...

7

Creating a Window

import javax.swing.*;

public class Basic1 { public static void main(String[] args) { //create the window JFrame f = new JFrame("Basic Test!"); //quit Java after closing the window f.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); f.setSize(200, 200); //set size in pixels f.setVisible(true); //show the window } }

8

Creating a Window Using a Constructor

import javax.swing.*; public class Basic2 extends JFrame {

public static void main(String[] args) { new Basic2(); } public Basic2() { setTitle("Basic Test2!"); //set the title //quit Java after closing the window setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); setSize(200, 200); //set size in pixels setVisible(true); //show the window } }

9

A More Extensive Example

import javax.swing.; import java.awt.; import java.awt.event.*; public class Intro extends JFrame { private int count = 0; privateprivate JButtonJLabel labelmyButton = new = newJLabel("Count: JButton("Push " +Me!"); count);

publicsetDefaultCloseOperation(JFrame. Intro() { EXIT_ON_CLOSE ); setLayout(new FlowLayout(FlowLayout. LEFT )); //set layout manager add(myButton);add(label); //add components label.setPreferredSize(new Dimension(60, 10)); myButton.addActionListener(new ActionListener() { publiccount++; void actionPerformed(ActionEvent e) { }label.setText("Count:^ "^ +^ count); }); pack(); setVisible(true); } publictry static{ void main(String[] args) { UIManager. setLookAndFeel (UIManager. getSystemLookAndFeelClassName ()); }new catch Intro(); (Exception exc) {} } } 10

GUI Statics

y Determine which components you want

y Choose a top-level container in which to put the

components (JFrame is often a good choice)

y Choose a layout manager to determine how

components are arranged

y Place the components

Components = What You See

y Visual part of an interface

y Represents something with position and size

y Can be painted on screen and can receive events

y Buttons, labels, lists, sliders, menus, ...

Component Examples

import javax.swing.; import java.awt.; public class ComponentExamples extends JFrame { public ComponentExamples() { setLayout(new FlowLayout(FlowLayout. LEFT )); add(new JButton("Button")); add(new JLabel("Label")); add(new JComboBox(new String[] { "A", "B", "C" })); add(new JCheckBox("JCheckBox")); add(new JSlider(0, 100)); add(new JColorChooser()); setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); pack(); setVisible(true); } public static void main(String[] args) { try { UIManager. setLookAndFeel (UIManager. getSystemLookAndFeelClassName ()); } catch (Exception exc) {} new ComponentExamples(); } }

19

BorderLayout Example

import javax.swing.; import java.awt.; public classpublic static Statics2 void {main(String[] args) { new S2GUI(); } } class ColoredJPanel extends JPanel { Color color; ColoredJPanel(Color color) { this.color = color; } public void paintComponent(Graphics g) { g.setColor(color); g.fillRect(0, 0, 400, 400); } } class S2GUI extends JFrame { public S2GUI() { setTitle("Statics2"); setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); setSize(400, 400); add(new ColoredJPanel(Color. RED ), BorderLayout. NORTH ); add(new ColoredJPanel(Color. GREEN ), BorderLayout. SOUTH ); add(new ColoredJPanel(Color. BLUE ), BorderLayout. WEST ); add(new ColoredJPanel(Color. YELLOW ), BorderLayout. EAST ); add(new ColoredJPanel(Color. BLACK ), BorderLayout. CENTER ); setVisible(true); } } 20

GridLayout Example

import javax.swing.; import java.awt.; public class Statics3 { public static void main(String[] args) { new S3GUI(); } } class S3GUI extends JFrame { static final int DIM = 25; static final int SIZE = 12; static final int GAP = 1; publicsetTitle("Statics3"); S3GUI() { setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); setLayout(new GridLayout( DIM , DIM , GAP , GAP )); for (int i = 0; i < DIM * DIM ; i++) add(new MyPanel()); pack(); setVisible(true); } class MyPanel extends JPanel { MyPanel() { setPreferredSize(new Dimension( SIZE , SIZE )); } public void paintComponent(Graphics g) { float gradient = 1f - ((float)Math. abs (getX() - getY()))/(float)(( SIZE + GAP ) * DIM ); g.setColor(new Color(0f, 0f, gradient));g.fillRect(0, 0, getWidth(), getHeight()); } } }

21

More Layout Managers

y CardLayout

ยƒ Tabbed index card look from Windows

y GridBagLayout

ยƒ Most versatile, but complicated

y Custom ยƒ Can define your own layout manager ยƒ But best to try Java's layout managers first...

y Null ยƒ No layout manager ยƒ Programmer must specify absolute locations ยƒ Provides great control, but can be dangerous because of platform dependency (^22)

AWT and Swing

y AWT ยƒ Initial GUI toolkit for Java ยƒ Provided a โ€œJavaโ€ look and feel ยƒ Basic API: java.awt.*

y Swing ยƒ More recent (since Java 1.2) GUI toolkit ยƒ Added functionality (new components) ยƒ Supports look and feel for various platforms (Windows, Motif, Mac) ยƒ Basic API: javax.swing.*

y Did Swing replaced AWT? ยƒ Not quite: both use the AWT event model

Code Examples

y Intro.java ยƒ Button & counter

y Basic1.java ยƒ Create a window

y Basic2.java ยƒ Create a window using a constructor

y Calculator.java ยƒ Shows use of JOptionPane to produce standard dialogs

y ComponentExamples.java ยƒ Sample components y Statics1.java ยƒ FlowLayout example y Statics2.java ยƒ BorderLayout example y Statics3.java ยƒ GridLayout example y LayoutDemo.java ยƒ Multiple layouts

GUI Dynamics

25

GUI Statics and GUI Dynamics

y Statics: whatโ€™s drawn on the screen ยƒ Components ยŠ buttons, labels, lists, sliders, menus, ... ยƒ Containers: components that contain other components ยŠ frames, panels, dialog boxes, ... ยƒ Layout managers: control placement and sizing of components

y Dynamics: user interactions ยƒ Events ยŠ button-press, mouse-click, key-press, ... ยƒ Listeners: an object that responds to an event ยƒ Helper classes ยŠ Graphics, Color, Font, FontMetrics, Dimension, ...

26

Dynamics Overview

y Dynamics = causing and responding to actions

ยƒ What actions? events ยŠ Need to write code that knows what to do when an event occurs ยƒ In Java, you specify what happens by providing an object that โ€œhearsโ€ the event ยŠ In other languages, you specify what happens in response to an event by providing a function

y What objects do we need?

ยƒ Events ยƒ Event listeners

Event listener

Event listener

Java VM

27

importimport javax.swing.;java.awt.; import java.awt.event.*; public class Intro extends JFrame { private int count = 0; private JButton myButton = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); publicsetDefaultCloseOperation(JFrame. Intro() { EXIT_ON_CLOSE ); setLayout(new FlowLayout(FlowLayout. LEFT )); //set layout manager add(myButton);add(label); //add components label.setPreferredSize(new Dimension(60, 10)); myButton.addActionListener(new ActionListener() { publiccount++; void actionPerformed(ActionEvent e) { label.setText("Count: " + count); });} pack(); setVisible(true); } public static void main(String[] args) { try (^) UIManager.{ setLookAndFeel (UIManager. getSystemLookAndFeelClassName ()); }new catch Intro(); (Exception exc) {} } }

Brief Example Revisited

28

importimport javax.swing.;java.awt.; import java.awt.event.*; public class Intro extends JFrame { private int count = 0; private JButton myButton = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); publicsetDefaultCloseOperation(JFrame. Intro() { EXIT_ON_CLOSE ); setLayout(new FlowLayout(FlowLayout. LEFT )); //set layout manager add(myButton);add(label); //add components label.setPreferredSize(new Dimension(60, 10)); myButton.addActionListener(new ActionListener() { publiccount++; void actionPerformed(ActionEvent e) { label.setText("Count: " + count); });} pack(); setVisible(true); } public static void main(String[] args) { try (^) UIManager.{ setLookAndFeel (UIManager. getSystemLookAndFeelClassName ()); }new catch Intro(); (Exception exc) {} } }

Brief Example Revisited

The Java Event Model

y Timeline

ยƒ User (or program) does something to a component ยŠ clicks on a button, resizes a window, ... ยƒ Java issues an event object describing the event ยƒ A special type of object (a listener) โ€œhearsโ€ the event ยŠ The listener has a method that โ€œhandlesโ€ the event ยŠ The handler does whatever the programmer programmed

y What you need to understand

ยƒ Events : How components issue events ยƒ Listeners : How to make an object that listens for events ยƒ Handlers : How to write a method that responds to an event

Events

y An Event is a Java object ยƒ It represents an action that has occurred โ€“ mouse clicked, button pushed, menu item selected, key pressed, ... ยƒ Events are normally created by the Java runtime system ยŠ You can create your own events, but this is unusual

y Most events are in java.awt.event ยƒ Some events are in javax.swing.event y All events are subclasses of AWTEvent

AWTEvent ActionEvent ComponentEvent InputEvent MouseEvent KeyEvent

37

Example 2: The Listener is an Inner Class

import javax.swing.; import java.awt.; import java.awt.event.*; public class ListenerExample2 extends JFrame { private int count; private JButton b = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); class Helper implements ActionListener { public void actionPerformed(ActionEvent e) { count++; label.setText("Count: " + count); } } public static void main(String[] args) { JFrame f = new ListenerExample2(); f.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); f.setSize(200,100); f.setVisible(true); } public ListenerExample2() { setLayout(new FlowLayout(FlowLayout. LEFT )); add(b); add(label); b.addActionListener(new Helper()); } } 38

Example 3: The Listener is an Anonymous Class

import javax.swing.; import java.awt.; import java.awt.event.*; public class ListenerExample3 extends JFrame { private int count; private JButton b = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); public static void main (String[] args) { JFrame f = new ListenerExample3(); f.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); f.setSize(200,100); f.setVisible(true); } public ListenerExample3() { setLayout(new FlowLayout(FlowLayout. LEFT )); add(b); add(label); b.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { count++; label.setText("Count: " + count); } }); } }

39

Adapters

y Some listeners (e.g., MouseInputListener) have

lots of methods; you donโ€™t always need all of them

ยƒ For instance, you may be interested only in mouse clicks

y For this situation, Java provides adapters

ยƒ An adapter is a predefined class that implements all the methods of the corresponding Listener ยŠ Example: MouseInputAdapter is a class that implements all the methods of interface MouseInputListener ยƒ The adapter methods do nothing ยƒ To easily create your own listener, you extend the adapter class, overriding just the methods that you actually need

40

Using Adapters

import javax.swing.; import javax.swing.event.; import java.awt.; import java.awt.event.; public class AdapterExample extends JFrame { private int count; private JButton b = new JButton("Mouse Me!"); private JLabel label = new JLabel("Count: " + count); class Helper extends MouseInputAdapter { public void mouseEntered(MouseEvent e) { count++; label.setText("Count: " + count); } } public static void main(String[] args) { JFrame f = new AdapterExample(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200,100); f.setVisible(true); } public AdapterExample() { setLayout(new FlowLayout(FlowLayout.LEFT)); add(b); add(label); b.addMouseListener(new Helper()); } }

Notes on Events and Listeners

y A single component can have many listeners

y Multiple components can share the same listener

ยƒ Can use event.getSource() to identify the component that generated the event

y For more information on designing listeners, see

http://java.sun.com/docs/books/tutorial/

uiswing/events/generalrules.html

y For more information on designing GUIs, see

http://java.sun.com/docs/books/tutorial/

uiswing/

GUI Drawing and Painting

y For a drawing area, extend JPanel and override the method public void paintComponent(Graphics g)

y paintComponent contains the code to completely draw everything in your drawing panel

y Do not call paintComponent directly โ€“ instead, request that the system redraw the panel at the next convenient opportunity by calling myPanel.repaint()

y repaint() requests a call paintComponent() โ€œsoonโ€ ยƒ repaint(ms) requests a call within ms milliseconds ยŠ Avoids unnecessary repainting ยŠ 16ms is a good default value

Java Graphics

y The Graphics class has methods for colors, fonts, and various shapes and lines ยƒ setColor(Color c) ยƒ drawOval(int x, int y, int width, int height) ยƒ fillOval(int x, int y, int width, int height) ยƒ drawLine(int x1, int y1, int x2, int y2) ยƒ drawString(String str, int x, int y)

y Take a look at ยƒ java.awt.Graphics (for basic graphics) ยƒ java.awt.Graphics2D (for more sophisticated control) ยƒ The 2D Graphics Trail: http://java.sun.com/docs/books/tutorial/2d/index.html