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

Slides:



Advertisements
Similar presentations
Graphic User Interfaces Layout Managers Event Handling.
Advertisements

User Interface Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 9 Object Oriented Programming in Java Advanced Topics Abstract Windowing.
Understanding SWING Architecture CS 4170 UI Design Hrvoje Benko Oct. 9, 2001.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
Advanced Java Class GUI – part 1. Intro to GUI GUI = Graphical User Interface -- “Gooey” Just because it’s “gooey” does not mean you may write messy code.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Graphical User Interface (GUI) Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
GUI Programming in Java Tim McKenna GUI Programming Concepts l conventional programming: sequence of operations is determined by the program.
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
GUI Programming in Java
Software Construction Lecture 10 Frameworks
Java Swing, Events and MVC Optional Readings: Eckel’s Thinking in Java: Chap 14 (
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI building with Swing. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Chapter 9: Visual Programming Basics Object-Oriented Program Development Using Java: A Class-Centered Approach.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
 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.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
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.
CSCI Swing1 The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness –The Abstract.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
CS Fall 2012, Lab 09 Haohan Zhu. Boston University Slideshow Title Goes Here CS Fall 2012, Lab /20/2015 GUI - Graphical User Interface.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
9.1 Java Packages A collection of classes Allows classes to be grouped arbitrarily Hierarchical structure independent of inheritance Classes can.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Week 6: Basic GUI Programming Concepts in Java Example: JFrameDemo.java container : a screen window/applet window/panel that groups and arranges components.
CS 4244: Internet Programming User Interface Programming in Java 1.0.
Creating Graphics in Java CSE301 University of Sunderland Harry R Erwin, PhD.
Swing - 2 Session 13. Swing - 2 / 2 of 38 Objectives (1) Discuss trees and tables Discuss progress bars Discuss MVC architecture Describe menus.
5-Jan-16 R Ramesh Swing. 5-Jan-16 R Ramesh An Introduction to Java Foundation Classes (JFC) A suite of libraries to assist programmers create enterprise.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Java Swing, Events Readings: Just Java 2: Chap 19 & 21, or Eckel’s Thinking in Java: Chap 14 Slide credits to CMPUT 301, Department of Computing Science.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Graphical User Interface (GUI)
1 Lecture 8: User Interface Components with Swing.
Developing GUIs With the Eclipse Visual Editor, Swing/AWT Edition David Gallardo.
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Chapter 6 Building Java GUIs. MVC Model View Controller The model passes its data to the view for rendering The view determines which events are passed.
GUI 1: JFC and Swing Basics OOP tirgul No
A Quick Java Swing Tutorial
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Advanced Programming in Java
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:

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))

Example import 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 { /** 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) 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 and Setting Up the Observer Box thePanel = Box.createVerticalBox(); //set up situation pane thePanel.add(new JLabel("The Situation")); Box theSituationPanel = createSituationPanel(); // creates a typical component thePanel.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 Constructor private JTextField createAShip() { final JTextField bFactors = new JTextField(); // gets preserved bFactors.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 model bFactors.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 definition bFactors.addFocusListener(bFactorsAdapter);// event handler return 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.