Chapter 18 Building the user interface. This chapter discusses n Javas graphical user interface. n Swing: an enhancement of a library called the Abstract.

Slides:



Advertisements
Similar presentations
Computer Science 112 Fundamentals of Programming II User Interfaces
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Guide to Programming with Python
Chapter 5 - Making Music: An On-Screen Piano
A.k.a. GUI’s.  If you want to discuss your Lab 2 grade come see me this week. ◦ Office: 436 ERB. One hour prior to class ◦ Open to Appointments MWF 
Java Programming Chapter 10 Graphical User Interfaces.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Draw Shapes Introduction to simple graphics. What is a Component? A class that resides in the java.awt package Examples include: –Button, java.awt.Button.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Welcome to CIS 083 ! Events CIS 068.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Field Trip #26 Create a Find a Word Puzzle in Java By Keith Lynn.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Intro to GUIs (Graphical User Interfaces) Section 2.5Intro. to GUIs: a GUI Greeter Section 3.7Graphical/Internet Java: Einstein's Equation.
Putting together a complete system Chapter 10. Overview  Design a modest but complete system  A collection of objects work together to solve a problem.
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
FLTK Help Session By Richard Yu Gu CS 638 -Graphics Fall, 1999.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
CS Lecture 00 Swing overview and introduction Lynda Thomas
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Java Programming: Advanced Topics 1 Components and Facilities for Rich Graphical User Interfaces Chapter 7.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
Applets Yong Choi School of Business CSU, Bakersfield.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
Creating Windows. How can we use Java to create programs that use windows (GUI applications)? How can we use Java to create programs that use windows.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 – Graphical User Interfaces Java Foundations: Introduction to Programming.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Basics of GUI Programming Chapter 11 and Chapter 22.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
1 Applets. 2 What is an applet? Applet: a Java program that can be inserted into a web page and run by loading that page in a browser brings web pages.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Lecture # 6 Graphical User Interface(GUI). Introduction A graphical user interface (GUI) presents a user- friendly mechanism for interacting with an application.
Java - hello world example public class HelloWorld { public static void main (String args[]) { System.out.println("Hello World"); }
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
1 Lecture 8: User Interface Components with Swing.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
12-Jun-16 Event loops. 2 Programming in prehistoric times Earliest programs were all “batch” processing There was no interaction with the user Input Output.
A Quick Java Swing Tutorial
A First Look at GUI Applications
Event loops 16-Jun-18.
Abstract Window ToolKit (AWT)
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Event loops.
Event loops 17-Jan-19.
Event loops 17-Jan-19.
Event loops 8-Apr-19.
Event loops.
Event loops.
Event loops 19-Aug-19.
Presentation transcript:

Chapter 18 Building the user interface

This chapter discusses n Javas graphical user interface. n Swing: an enhancement of a library called the Abstract Window Toolkit (AWT). n Event-driven, window-based applications. n Swing as a case study of how large libraries are organized.

The system interface n The interface and the model are two of the principal components of a software system. n The interface handles interaction with the external world. n When the external world is a person, the interface is called a user interface.

Algorithm-driven interfaces n In an algorithm-driven approach, the application determines exactly what information it needs from the environment, and when it needs it. n The application has access to several streams of data. n A stream is a sequence of bytes.

Algorithm-driven interfaces (cont.) n A character stream is a set of ASCII characters. n Otherwise it is a binary stream. n Input stream sources can be a users keyboard, a file, another program, an external device, etc. n Output stream targets can be a users display screen, a file, another program, an external device, etc.

Java compiler stream n 1 input stream n 2 output streams

Nim game user interface Enter number of Sticks. 3 Player Player1 takes 2 leaving 1 sticks. Player Player2 takes 1 leaving 0 sticks. Game over. Player 1 won. To Play again, enter 1; to stop enter 0 1 Enter number of sticks. n This game writes output and reads input.

Filters n Where input data comes from and where output data goes often is not important to the application. n Filters read input from a single stream called standard input, write output to an output stream called standard output, and write error messages to a stream called standard error.

Event-driven interfaces n The application is active in an algorithm-driven interface; it is passive in an event-driven system. n An event-driven system waits for something to happen (an event) in the environment. n event-driven: an input-output model in which the application waits for an event to occur, responds to the event, and waits for the next event.

Event-driven interfaces (cont.) n An application with a window-based interface provides a graphical control panel containing a range of options.

Event-driven interfaces (cont.) n In a window-based system, we assume that there is a native windowing system that actually detects events like mouse clicks, mouse movement, key strokes, etc., and manages the display. n Java applications interact with the native windowing system.

Swing n A graphical user interface is made up of components (widgets). u windows u buttons u menus, etc. n Each components has attributes of location, size, shape, color, etc. Components are defined in a class library contained in the package javax.swing

JComponent abstract class

JComponent abstract class (cont.)

n JComponent is a subclass of the AWT. public Color getForeground (); public Color getBackground (); public Point getLocation (); public Dimension getSize (); public void Color setForeground(Color fg); public void Color setBackground(Color bg); public void Point setLocation(Point p); public void Dimension setSize(Dimension d;)

JComponent abstract class (cont.) Many of the methods are overloaded. For instance, there are versions of setLocation and setSize that take two int arguments rather than a Point or Dimension.

JComponent abstract class (cont.) n Color, Point, and Dimension are AWT classes. n Instances of Color are immutable. The class Color defines a number of constant references. i.e. Color.red Class Dimension encapsulates width and height.

Containers n Objects that contain components are containers. n JComponent is a subclass of Container. n component: a distinct element of a graphical user interface, such as a button, text field, etc. n container: a graphical user interface component that can contain other components.

Containers (cont.)

JPanel n Used as a place to put a collection of other components. Jpanel p = new Jpanel(); p.add(new Jbutton(on)); p.add(new Jbutton(off));

Manipulating content n Class Container defines an extensive set of methods for manipulating its content. public int getComponentCount() The number of Components in this Container. public Component getComponent (int n) The Component with the specified index. require: 0 <= n < this.getComponentCount() public void remove (Component comp) Remove the specified Component. public void remove (int index); Remove the Component with the specified index. require: 0 <= index < this.getComponentCount()

Top-level containers n A top-level container is one that is not contained in any other container. i.e. JApplet, JDialog, JFrame, and JWindow.

JFrame n A window with a title and a border. n JFrame is a subclass of java.awt.Container, not JComponent. n It delegates the responsibility of managing its components to another object--JRootPane.

JRootPane n JRootPane is a JComponent whose principal responsibility is to manage the content of some other container. n It is a composite object, including a content pane. n The content pane is usually a JPanel, and is the working area of the JFrame, excluding title, border, menu. n Components are not added directly to the JFrame, but to the content pane.

JRootPane (cont.) getContentPane returns a Container. JFrame f = new JFrame(A Frame); JButton b = new JButton(Press); Container cp = f.getContentPane(); cp.add(b); n JApplet, JDialog, JWindow and JInternalFrame also use JRootPane to manage components.

Peers n JApplet, JDialog, JFrame, JWindow are heavyweight components. n Instances of subclasses of JComponent are lightweight components. n When a heavyweight component is created, the AWT also creates an associated native GUI component called a peer. i.e. Creation of JFrame, also creates a frame peer.

Peers (cont.) n Peers actually do the work of capturing user input and managing the screen area in which the component is displayed. n Lightweights are implemented completely by Java. n Lightweights are drawn on the space provided by their heavyweight parent containers.

Top-level frame import javax.swing.*; public class DisplayFrame { public static void main (String[] args){ JFrame f = new JFrame (A Frame); f.setSize(300,200); f.setVisible(true); }

Adding components n Adding components to the frame wont cause the component to appear suddenly on the display. n A LayoutManager is an object responsible for positioning and sizing the components in a container. A LayoutManager is specified in the interface java.awt.LayoutManager. public LayoutManager getLayout(); public void setLayout (LayoutManager manager);

LayoutManager implementations n FlowLayout: left to right, top to bottom. n BorderLayout: north, south, east, west, center. n GridLayout: two-dimensional grid. n CardLayout: one at a time from a deck n GridBagLayout: vertically and horizontally according to constraints. n BoxLayout: either a single horizontal row or single vertical column. n OverlayLayout: specified components align in the same place; components are laid out on top of each other.

FlowLayout

BorderLayout

GridLayout

n When the GridLayout is created, we specify that we want a grid of 3 rows and 2 columns. Since there is more than 6 components, GridLayout expands the number of columns, while keeping the number of rows at 3.

Container validity n A Container is valid if it does not need to be laid out. i.e. size is known to the system, and the layout manager knows about all its components. n A Container is invalid if its state is inconsistent with its appearance. n A Container to which a component has been added after it was last laid out is invalid.

Container validity (cont.) n Any number of things can cause the layout manager to lay out the Container. validate explicitly sets the Containers valid property to true, and instructs the layout manager to lay out the Container. isValid returns the value of this property. public boolean isValid(); public void validate();

Capturing and handling events n event: the occurrence of an action, typically external to the system, that the system is aware of and must respond to. n low-level events: pressing or releasing a key, moving the mouse, pressing a mouse button. n high-level events: selecting an item on the menu, pressing a button, entering text in a field. u High-level events usually involve one or more low-level events.

Some high-level events n key event: a keyboard key pressed or released. n mouse event: the mouse is moved or dragged, a button pressed or released, the mouse cursor enters or exits component. n component event: a component is hidden, shown, resized, or moved. n container event: a component is added to or removed from a container. n window event: a window is opened, closed, iconified, de-iconified, activated, deactivated.

Some high-level events (cont.) n focus event: a component gains or loses focus. n action event: a high-level event occurs. n adjustment event: a high-level event occurs representing scrollbar motions. n item event: a high-level event occurs when user selects a checkbox, choice, or list item. n document event: a TextComponents content changes.

Java event classes

Java event classes (cont.) n The source of an event is determined with: public Object getSource(); n An object that monitors when an event occurs is called a listener. n To be notified of an event, a listener must register with the events source. n The relation between a listener and an event source is the observes relation.

Example import java.awt.*; import javax.swing.*; import java.awt.event.*; public class OnOffTest { public static void main (String[] args){ OnOffSwitch sw = new OnOffSwitch(); } class OnOffSwitch extends JFrame { public OnOffSwitch() { super(On/Off Switch); JButton button= new JButton(On/Off); Container cp = this.getContentPane(); button.setForground(Color.black); button.setBackground(Color.white); cp.add(button,BorderLayout.Center); this.setSize(300,200); this.setVisible(true); }

Example

EventListener classes

Adding a listener n There is only one method specified in the interface ActionListener. public void actionPerformed(ActionEvent e); class Switcher implements ActionListener { public void actionPerformed (ActionEvent e) {…} } n When the user presses the button, an ActionEvent is generated.

Example class OnOffSwitch extends JFrame { public OnOffSwitch() { super(On/Off Switch); JButton button= new JButton(On/Off); Switcher control = new Switcher(); button.addActionListener(control); Container cp = this.getContentPane(); button.setForground(Color.black); button.setBackground(Color.white); cp.add(button,BorderLayout.Center); this.setSize(300,200); this.setVisible(true); }

Example (cont.) public void actionPerformed(ActionEvent e){ Component source = (Component)e.getSource(); Color oldForeground = source.getForegound(); source.setForeground (source.getBackground()); source.setBackground(oldForeground); }

Example (cont.)

n Since the listener explicitly determines the source of the event, it could handle events from several sources without modification. class OnOffSwitch extends JFrame { public OnOffSwitch() { super(On/Off Switch); JButton button1= new JButton(On/Off); JButton button2= new JButton(On/Off); Switcher control = new Switcher(); button1.addActionListener(control); button2.addActionListener(control); … }

Adding a window listener n We would like to terminate the application when the user selects the Close option from the top-level window menu. n Selecting Close generates a WindowEvent in the JFrame, specifically a window closing event. n The WindowListener interface is a bit more complicated than the ActionListener interface; it specifies seven methods.

Adding a window listener (cont.) void windowActiviated (WindowEvent e) Invoked when window becomes the active window. void windowClosed (WindowEvent e) Invoked when window has been closed. void windowClosing (WindowEvent e) Invoked when user attempts to close window. void windowDeactiviated (WindowEvent e) Invoked when window becomes no-longer-active window. void windowDeiconified (WindowEvent e) Invoked when window changes from minimized to normal. void windowIconified (WindowEvent e) Invoked when window changes from normal to minimized. void windowOpened (WindowEvent e) Invoked when window is first made visible.

Adding a window listener (cont.) To simplify the implementation, Java provides event adapter classes. class Terminator extends WindowAdapter { public void windowClosing(WindowEvent e) { Window w = e.getWindow(); w.dispose(); } public void windowClosed(WindowEvent e) { System.exit(0); }

Adding a window listener (cont.) We must create a Terminator instance and register it with the top-level JFrame. public OnOffSwitch() { super(On/Off Switch); JButton button= new JButton(On/Off); Switcher control = new Switcher(); Terminator arnold = new Terminator(); button.addActionListener(control); this.addWindowListener(arnold); … }

Adding a window listener (cont.) n Terminator is an ideal candidate for being made an anonymous inner class. this.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); } public void windowClosed(WindowEvent e) { System.exit(0); } );

Some class features

Component n Background color: public Color getBackground() public void setBackground(Color c) n Foreground color: public Color getForeground() public void setForeground(Color c) n Location: public Point getLocation() public void setLocation(int x, int y) public void setLocation(Point p) n Location on screen: public Point getLocationOnScreen() n Size: public Dimension getSize() public void setSize(int height,int width) public void setSize(Dimension d)

Component (cont.) n Preferred size: public Dimension getPreferredSize() n Minimum size: public Dimension getMinimumSize() n Parent: public Container getParent() n Enable: public boolean isEnabled() public void setEnabled(boolean enabled) n Valid: public boolean isValid() public void validate() public void invalidate()

Component (cont.) n Visible and Showing: public boolean isVisible() public boolean isShowing() public void setVisible(boolean visible) n Font: public Font getFont() public void setFont(Font f) n Graphics: public Graphics getGraphics() n Listeners: public void addComponentListener( ComponentListener listener) public void removeComponentListener( ComponentListener listener)

Component (cont.) n Listeners (cont.): public void addFocusListener( FocusListener listener) public void removeFocusListener( FocusListener listener) public void addKeyListener( KeyListener listener) public void removeKeyListener( KeyListener listener) public void addMouseListener( MouseListener listener) public void removeMouseListener( MouseListener listener) public void addMouseListener( MouseMotionListener listener) public void removeMouseListener( MouseMotionListener listener)

Containers n Component Manipulation: public int getComponentCount() public Component getComponent(int position) public Component getComponentAt(int x, int y) public Component getComponent(Point p) n Component Manipulation (cont.): public Component add(Component component) public Component add(Component component, int position) public Component add(Component component, Object constraints) public void remove(Component component) public void remove(int position)

Containers (cont.) n Layout Manager: public int getLayout() public void setLayout(LayoutManager manager) n Listeners: public void addContainerListener( ContainerListener listener) public void removeContainerListener( ContainerListener listener)

Window public void pack() public void toFront() public void toBack() public void dispose() n Listeners: public void addWindowListener( WindowListener listener) public void removeWindowListener( WindowListener listener)

Frame n Title: public String getTitle() public void setTitle(String title) n Resizable: public boolean isResizable() public void setResizable(boolean visible) n Border: public Border getBorder() public void setBorder(Border border) n Ancestors: public JRootPane getRootPane() public Container getTopLevelAncestor() n Transparency: public void setOpaque(boolean isOpaque) public boolean isOpaque()

JFrame n Components: public Container getContentPane () public JMenuBar getJMenuBar () public JRootPane get JRootPane () public void setContentPane(Container contentPane) public void setJMenuBar(JMenuBar menubar) n Default close operation: public int getDefaultCloseOperation () public void setDefaultCloseOperation (int operation) One of the following must be passed to setDefaultCloseOperation. WindowConstants.DO_NOTHING_ON_CLOSE WindowConstants.HIDE_ON_CLOSE WindowConstants.DISPOSE_ON_CLOSE

Weve covered n Building a user interface. n Event-driven, graphical user interfaces. n Javas facilities for user interfaces. n Events. n Listeners.

Glossary

Glossary (cont.)