1 / 35

Creating Graphical User Interfaces (GUIs) in Java

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.

Download Presentation

Creating Graphical User Interfaces (GUIs) in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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.

  3. 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.

  4. 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?)

  5. 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.

  6. 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.

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

  8. 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.

  9. 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

  10. 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.

  11. 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.

  12. 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

  13. 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.

  14. AWT Features • Basic facilities for creating a graphical user interface • Drawing graphics (not covered in this module)

  15. 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.

  16. 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(

  17. 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.

  18. Creating the Graphical User Interface • This is a four-step process (see Flanagan, Java Foundation Classes in a Nutshell): • Create and configure the components. This uses the standard Java syntax for reference types. • Add the components to a container. ‘Containers’ are subclasses of java.awt.Container. • Arrange or lay out the components. Do it yourself, or use a LayoutManager. • Handle the events generated by the components. You add event listeners to do this. • We will explore this.

  19. 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.

  20. Button Canvas Checkbox CheckboxMenuItem Choice Component FileDialog Label List Menu MenuBar MenuComponent MenuItem PopupMenu Scrollbar TextArea TextComponent TextField AWT Component List

  21. J‘AWT-name’ for most AWT components JColorChooser JComboBox JEditorPane JFileChooser JOptionPane JPasswordField JProgressBar JRadioButton JRadioButtonMenuItem JSeparator JSlider JTable JTextPane JToggleButton JToolBar JToolTip JTree Swing Component List

  22. 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.

  23. AWT Containers • Applet • Container • Dialog • Frame • Panel • ScrollPane • Window

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

  25. 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

  26. 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(

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

  28. 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.

  29. 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.

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

  31. 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 { /** * @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); } } );

  32. 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); } }

  33. Adding Content andSetting 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.

  34. 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; }

  35. 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.

More Related