creating graphical user interfaces (guis) in java

35
Creating Graphical User Interfaces (GUIs) in Java CSE301 University of Sunderland Harry R Erwin, PhD

Upload: nigel-phelps

Post on 30-Dec-2015

75 views

Category:

Documents


3 download

DESCRIPTION

Creating Graphical User Interfaces (GUIs) in Java. CSE301 University of Sunderland Harry R Erwin, PhD. Graphical User Interfaces. Are based on a real-world (typically desktop) metaphor. Apple’s user interface guidelines are a good starting point for understanding the semantics. - PowerPoint PPT Presentation

TRANSCRIPT

Creating Graphical User Interfaces (GUIs) in Java

CSE301

University of Sunderland

Harry R Erwin, PhD

Graphical User Interfaces

• Are based on a real-world (typically desktop) metaphor.

• Apple’s user interface guidelines are a good starting point for understanding the semantics.

• Programming a GUI is very strange and wonderful and often difficult.

• We will learn how to do this in Java.

Smalltalk History(Goldberg and Robson)

• Xerox PARC during the 1970s was exploring how computing power would be used in business. (Xerox sells products for the office environment.)

• They concentrated on two research areas:– A programming language to serve as an interface

between models in the mind and those in computing hardware.

– A user interface to match the human communication system to that of the computer.

• This resulted in the Smalltalk system.

The Smalltalk Approach

• Smalltalk was a graphical, interactive programming environment.

• Smalltalk was a big system, built on a model of communicating objects.

• Smalltalk’s primary vocabulary was: – object, – message, – class, – instance, and – method. (Sounds familiar?)

The Desktop Metaphor

• Xerox invented the desktop metaphor for SmallTalk:– The display screen contains one or more rectangular

areas called views.– Views may overlap.– Each view has a title.– The mouse has three buttons:

• Left—select.• Middle—action menu popup.• Right—view menu popup.

Apple’s Guidelines (Apple 2002)

• Apple made the desktop metaphor more explicit:– File folders– Documents– Wastebasket

• Operations based on “see and point”– The user selects an object on the screen, and – Then applies a verb to it.

• Direct manipulation– Objects remain visible– Effects of actions are immediately visible.

Apple Guidelines (II)

• User control– The user, not the computer, initiates and controls

actions.

• Feedback and communication– Keep users informed about what’s happening

• Progress indicators• Immediate direct feedback

• Consistency– Avoid forcing the user to retrain to use your

application. Take advantage of their task knowledge.

Apple Guidelines (III)

• What you see is what you get (WYSIWYG)– No significant differences between what is seen on the

screen and what is printed by the printer. Applies to all data.– All commands should be easily found.

• Forgiveness– Make most actions easily reversible.

• Perceived stability– Be consistent.

• Aesthetic integrity– Make your displays pleasant to view over time.

Apple Guidelines (IV)

• Modelessness– Let the user do what she wants most of the time.

• Knowledge of your audience– Understand the user and the user’s expectations.

• Worldwide compatibility– Cultural values– Language differences– Text display/editing

• Accessibility for persons with disabilities

Then Why is Programming a GUI so Hard?

• In doing this, Apple decided that ease of use was more important than ease of programming.

• The GUI programming model was very different from most programmer’s previous experience in the 1980s.

• Very similar approaches (and implementations) are also present in most later systems:– X11– Windows– Java

• As a result, GUI programming is not easy in any of these systems.

General Approach

• All applications have an event-handling loop that receives asynchronous events from the GUI and services them.

• Events may trigger other events to be serviced.• Display is asynchronous with event handling, but

event servicing may change the display.• Organizing this system to support multiple views

or windows and both high and low-level events leads to a number of design approaches. We will study how Java does it.

Java GUI Frameworks

• Abstract Window Toolkit (java.awt)– The original set of windowing components designed for Java.

These were implemented as separate processes using the GUI features of the underlying operating system.

• Swing (or Java Foundation Classes—javax.swing)– A second generation set of ‘light-weight’ windowing components

introduced in Java 1.2. These were implemented as Java threads and so avoided the overhead of process context switches and enforced a common look and feel.

• SWT (part of Eclipse)• Discussed at:

http://java.sun.com/docs/books/tutorial/uiswing/index.html

AWT

• The foundation of GUI in Java

• Implemented in separate processes

• Rudimentary

• Supported by most web browsers, so that most applets should use AWT instead of Swing.

AWT Features

• Basic facilities for creating a graphical user interface

• Drawing graphics (not covered in this module)

Using AWT

• Import:– java.awt.*

– java.awt.event.*

• Everything inherits from java.awt.Component

• The AWT GUI is organized by containers, inheriting from java.awt.Container (which inherits from Component).

• The arrangement of controls is managed by various layout managers.

• Notification of changes is handled by events and event listeners that run in a GUI thread.

Swing

• Built on AWT• Written in pure Java• Uses less classes and is faster• Common look and feel• Designed to explicitly support the Model-View-

Controller pattern (future lecture).• Supports handicapped accessibility.• Not supported by all web browsers 8(

To Use Swing

• You must import the following:– java.awt.*– java.awt.event.*– javax.swing.*– javax.swing.event.*– javax.swing.border.*– javax.swing.text.*

• These are stored in– swing.jar– swingall.jar– windows.jar

• Point to these using your CLASSPATH.

Creating the Graphical User Interface

• This is a four-step process (see Flanagan, Java Foundation Classes in a Nutshell):

1. Create and configure the components. This uses the standard Java syntax for reference types.

2. Add the components to a container. ‘Containers’ are subclasses of java.awt.Container.

3. Arrange or lay out the components. Do it yourself, or use a LayoutManager.

4. Handle the events generated by the components. You add event listeners to do this.

• We will explore this.

Creating the Components

• These are the building blocks of your interface.• Flanagan’s Java Foundation Classes in a Nutshell

is a good reference. Study it to understand what components are available to you and how to use them. Remember the role inheritance plays in this.

• The names of Components often tell you exactly what they do.

• Every component has properties that can be used to configure it. The JavaBeans specification formalizes this.

AWT Component List

• Button

• Canvas

• Checkbox

• CheckboxMenuItem

• Choice

• Component

• FileDialog

• Label

• List

• Menu

• MenuBar

• MenuComponent

• MenuItem

• PopupMenu

• Scrollbar

• TextArea

• TextComponent

• TextField

Swing Component List

• J‘AWT-name’ for most AWT components

• JColorChooser• JComboBox• JEditorPane• JFileChooser• JOptionPane• JPasswordField• JProgressBar• JRadioButton

• JRadioButtonMenuItem

• JSeparator

• JSlider

• JTable

• JTextPane

• JToggleButton

• JToolBar

• JToolTip

• JTree

How to Add Components to a Container

• See Flanagan (Java Foundation Classes in a Nutshell) for the details.

• Most Container classes are specialized. You will most frequently use:– Applet (or JApplet)– JFrame – JDialog– JDesktopPane (with JInternalFrame)– JPanel

• You use the add() method to add Components to a Container. Since Containers are also Components, you can create a hierarchy of Containers, all displayed within a JFrame, JDesktopPane, or JApplet.

AWT Containers

• Applet

• Container

• Dialog

• Frame

• Panel

• ScrollPane

• Window

Swing Containers

• J‘AWT-name’ for AWT containers• Box• JDesktopPane• JInternalFrame• JLayeredPane• JRootPane• JSplitPane• JTabbedPane• JViewport

Laying out the Components

• You can design your own layout or use one of the LayoutManagers that Java provides.

• LayoutManager classes include:– BorderLayout– CardLayout– FlowLayout– GridBagLayout– GridLayout– BoxLayout (nice)– OverlayLayout– ScrollPaneLayout– ViewPortLayout

Event Handling

• The part of the project many students don’t get around to doing. To do anything, you have to handle events.

• java.awt and javax.swing use the event-handling API defined by the JavaBeans component model. This is based on events and event listeners.

• events extend java.util.EventObject.• event listeners extend java.util.EventListener.• Applets may have to use an older API for browser

compatibility. 8(

Warnings• java.awt.event and javax.swing.event mostly define

interfaces and event adapters. Event adapters are empty classes implementing specific interfaces that you can subclass very easily for your specific needs.

• You must define your own implementations, since this is the code that modifies your model.

• Events are dispatched by an automatically created thread called the event dispatch thread. You must synchronize with it if other threads modify your model. (See Lecture 20.)

Event Listeners

• The object notified of an event is an event listener.

• An event listener can handle several types of events, and more than one event listener can monitor a specific event.

• One of the most important things to know about a Component is what events it can generate, so read the documentation.

• Event listeners can register themselves with multiple components and can have other functions, as well.

• Event listener interfaces with more than one method generally have associated event adapters that you can use.

Component Events

• Low-level events reflect things like keypresses and mouse clicks. Avoid handling these unless you must.

• Individual Components can handle low-level events for you. For example a JButton handles mouse clicks and releases. Take advantage of this.

• Components generate higher-level ActionEvents for you to handle—e.g., button pushes. Sometimes, these events can also be handled for you. Your GUI initialization code needs to tell the system what events you want it to handle transparently in this way.

• See Chapter 10 of Java Examples in a Nutshell.

Using Inner Classes in your GUI

• To handle an event, you must implement the corresponding event listener. 8(

• It is quite common to create special classes to handle these events. 8(

• Inner classes were invented to simplify this. 8)• An inner class can implement an event listener

interface or extend an event adapter class. 8)• See Chapter 2 of Flanagan, Java Foundation

Classes in a Nutshell for lots of examples. 8))

Exampleimport java.awt.BorderLayout;import java.awt.Container;import java.awt.HeadlessException;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.util.Observable;import java.util.Observer;import javax.swing.JFrame;public class NavalCRTGUI extends JFrame implements Observer {

/** * @throws java.awt.HeadlessException */public NavalCRTGUI() throws HeadlessException {

super("ASW Results Analyzer");final NavalCRTGUI theGUI = this;// Handle window close requests (inner class)this.addWindowListener(

new WindowAdapter() {public void windowClosing(WindowEvent e)

{ System.exit(0); }}

);

Example (II)// All content of a JFrame (except for the menubar) goes in the// Frame's internal "content pane", not in the frame itself.// The same is true for JDialog and similar top-level containers.Container contentPane = this.getContentPane();contentPane.setLayout(new BorderLayout());

}/* (non-Javadoc) * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */public void update(Observable o, Object arg) {

// focus events will be used to update // the ASW state of the system// changes to the outputs will be reported as observables

}public static void main(String[] args) {

NavalCRTGUI display = new NavalCRTGUI();display.setSize(1000, 800);display.setVisible(true);

}}

Adding Content andSetting Up the Observer

Box thePanel = Box.createVerticalBox();// set up situation panethePanel.add(new JLabel("The Situation"));Box theSituationPanel = createSituationPanel();// creates a typical componentthePanel.add(theSituationPanel);

…((Observable)theBattle).addObserver((Observer)this);// this is the JFrame being built.update(theBattle,null);// the JFrame is an Observer and has an update// method. This// will result in the GUI being initialized// from the domain class. That is good.

Typical Component Constructorprivate JTextField createAShip() {

final JTextField bFactors = new JTextField(); // gets preservedbFactors.setText(String.valueOf(theBattle.getABomber(3).getFactors()));;FocusAdapter bFactorsAdapter = new FocusAdapter() { // inner class

public void focusLost(java.awt.event.FocusEvent event) {String s = bFactors.getText();try {

int f = Integer.parseInt(s);if (f < 0)

f = 0;else if (f > 99)

f = 99;theBattle.getABomber(3).setFactors(f);// the modelbFactors.setText(String.valueOf(f));

} catch (NumberFormatException e) {bFactors.setText("0");theBattle.getABomber(3).setFactors(0);// the model

}theBattle.recompute();// telling the model to recompute

}}; // end of inner class definitionbFactors.addFocusListener(bFactorsAdapter);// event handlerreturn bFactors;

}

Summary

• First create and configure your components. Create methods keep this clean.

• Add the components to containers. Remember, containers are also components, so you can nest them.

• Arrange or lay out the components. Do it yourself, or use a LayoutManager. Box layout is easy to use.

• Handle the events generated by the components. You must create event listeners to do this. These should usually be built using inner classes. (I usually do this in the Create methods.) These are the important hidden parts of the GUI that affect the rest of the system.