1 / 149

CIS 5930-04 – Spring 2001 Part 4: GUIs and Events

CIS 5930-04 – Spring 2001 Part 4: GUIs and Events. http://aspen.csit.fsu.edu/it1spring01 Instructors: Geoffrey Fox , Bryan Carpenter Computational Science and Information Technology Florida State University Acknowledgements: Nancy McCracken Syracuse University.

val
Download Presentation

CIS 5930-04 – Spring 2001 Part 4: GUIs and Events

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. CIS 5930-04 – Spring 2001 Part 4: GUIs and Events http://aspen.csit.fsu.edu/it1spring01 Instructors: Geoffrey Fox , Bryan Carpenter Computational Science and Information Technology Florida State University Acknowledgements: Nancy McCracken Syracuse University dbc@csit.fsu.edu

  2. Getting Started (and Getting Stopped) dbc@csit.fsu.edu

  3. GUI Components and Events • In the standard Java windowing toolkits, the GUI (Graphical User Interface) is built hierarchically in terms of components—one component nested inside another starting with the smallest buttons, including menus, text fields etc. and ending with full window divided into frames, menu bars, etc. • The user can interact with the GUI on many of its components, by clicking a button, typing in text, etc. These actions cause an event to be generated, which will be reported by the system to a class that is an event listener. The event listener will have an event handler methodfor the event. This method will provide the appropriate response to the user's action. dbc@csit.fsu.edu

  4. AWT vs. Swing • AWT (Abstract Windowing Toolkit) was the original windowing toolkit shipped with Java. • AWT components were designed to take on the “look and feel” of the underlying window system in which they are displayed. For applets—wherever the browser is running. • With the advent of the Java 2 platform, AWT is gradually being replaced by Swing—part of JFC. • Swing components are designed to have a fixed “look and feel” on all platforms. They are less prone to windowing system dependency bugs. • The default “platform look and feel”, abbreviatedplaf, is called Metal. Others available include Motif and Windows. • In this tutorial, where there is a choice, we will use Swing components in preference to AWT. dbc@csit.fsu.edu

  5. Creating a Frame • A top-level window is called a frame. • In Swing, it is represented by a class JFrame. • To display a frame, simply create an instance of the JFrame class, optionally set a few parameters, then invoke the show() method. • First few examples here are adapted from the Core Java book. dbc@csit.fsu.edu

  6. Simplest Test of the JFrame Class import javax.swing.* ; class FirstFrame extends JFrame { public FirstFrame() { setTitle(“FirstFrame”) ; setSize(450, 300) ; // Default size is 0 by 0 } } public class FrameTest { public static void main(String [] args) { JFrame frame = new FirstFrame() ; // Create JFrame. frame.show() ; // Display it. System.out.println(“main() done.”) ; // Done. } } dbc@csit.fsu.edu

  7. Running FrameTest $ java FrameTest main() done. dbc@csit.fsu.edu

  8. Trying to Terminate FrameTest. . . $ java FrameTest main() done. Click! dbc@csit.fsu.edu

  9. . . . the Window Vanishes, but . . . $ java FrameTest main() done. Still no prompt! dbc@csit.fsu.edu

  10. What Happened? • We notice that the main() method ends as soon as the window appears. But the command java FrameTestdoes notterminate. There is no new command prompt. • Closing the window using its system menu doesn’t change this. The command still does not terminate. • Why? dbc@csit.fsu.edu

  11. Threads and Termination • To explain this behavior, we should look to threads. • As will be discussed in detail later, a Java program can start extra threads during its execution. These run concurrently with the original thread (the thread in which the system started the main() method). • The JVM, and thus thejava command, terminates when the main() method has terminated andall threads the main() method created, directly or indirectly,have also terminated. • We can guess that FrameTest started one or more additional threads running, and those threads don’t terminate. • What were those threads? dbc@csit.fsu.edu

  12. The Event-dispatching Thread • . . . they don’t appear to be documented in detail, but one of them is surely the event-dispatching thread associated with the AWT system event queue. (Likely scenario: event queue classes are dynamically loaded when the first event-related operation occurs. When this happens an event dispatching thread is started. In the current case, opening a window creates the first event, and thus starts the thread.) • Event dispatching and the event queue will be discussed in more detail later. • But to make progress now, we must explicitly use the event mechanism to solve the problem of terminating FrameTest. dbc@csit.fsu.edu

  13. Strategy for Termination • In our example, we would like the javaFrameTest command to terminate when the window is closed. • When the user closes a window (e.g. by clicking the “close” item in the window’s system menu), the AWT system generates a WindowEvent. • A program (or part of a program) will be notified of this event if it has registered a listener for the window involved. • A listener is an instance of some programmer-defined class. The programmer defines methods in this class for handling all relevant events. • In our case, we want the listener to shut down the JVM when a window-closing event happens. dbc@csit.fsu.edu

  14. The WindowListener Interface • We need to listen for events relevant to top-level windows. The listener must implement the WindowListener interface: public interface WindowListener extends EventListener { void windowActivated(WindowEvent e) ; void windowClosed(WindowEvent e) ; void windowClosing(WindowEvent e) ; void windowDeactivated(WindowEvent e) ; void windowDeiconified(WindowEvent e) ; void windowIconified(WindowEvent e) ; void windowOpened(WindowEvent e) ; } This interface is defined in the java.awt.event package. dbc@csit.fsu.edu

  15. A Simple Listener Class • We only care about window-closing events (which happen when the user closes a window). Our implementation is: class TerminationListener implements WindowListener { public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e) { System.exit(0) ; // Shut down the JVM! } public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} } dbc@csit.fsu.edu

  16. A Windowing Program that Terminates import javax.swing.* ; import java.awt.event.* ; . . . Declaration of TerminationListener (previous slide) . . . class SimpleFrame extends JFrame { public SimpleFrame() { setTitle(“SimpleFrame”) ; setSize(450, 300) ; addWindowListener(new TerminationListener()) ; // Register listener for this window } } public class TerminationTest { public static void main(String [] args) { JFrame frame = new SimpleFrame() ; // Create JFrame. frame.show() ; // Display it. } } dbc@csit.fsu.edu

  17. Simple Use of Swing Components dbc@csit.fsu.edu

  18. Internal Structure of a JFrame • A Swing frame has a fairly complicated structure, with several panes. Some of these are used to implement pluggable look and feel. We will only directly use the Content Pane. Title JFrame JRoot Optional menu bar Content pane Glass pane dbc@csit.fsu.edu

  19. Swing Component Hierarchy JComponent JLabel AbstractButton JButton JComboBox JMenuItem JToggleButton JScrollbar JMenu JList JPanel JCheckbox JMenuBar JRadioButton JTextComponent JTextArea JTextfield dbc@csit.fsu.edu

  20. Atomic Components and Containers • For each atomic component, one can create one or more instances of the component type and then use the add() methods to place them into a container component, such as a panel. • For now, we assume that components are added to the panel in order from left to right and top to bottom, as they fit. • This is the default layout strategy forJPanels—flow layout. • For JFrames, the content pane is a container obtained by using the getContentPane() method. Typically we add() a JPanelcontaining further components to this pane. • The content pane itself hasborder layout by default, which means it can only directly display a single component in its center field. dbc@csit.fsu.edu

  21. A Panel with Buttons • We will derive a class from JPanel. The constructor adds three buttons with labels “Red”, “Blue” and “Green”. class ButtonPanel extends JPanel . . . { public ButtonPanel { redButton = new JButton(“Red”) ; blueButton = new JButton(“Blue”) ; greenButton = new JButton(“Green”) ; add(redButton) ; add(blueButton) ; add(greenButton) ; . . . } . . . private JButton redButton ; private JButton blueButton ; private JButton greenButton ; } dbc@csit.fsu.edu

  22. Action Listeners • When a button is pushed, it creates an ActionEvent. • To respond to this kind of event, the application must provide a listener implementing the ActionListener interface. • Simpler than the WindowListener—it only has one method: interface ActionListener extends EventListener { public void actionPerformed(ActionEvent evt) ; } • The listener may be implemented by a purpose-built class, like earlier TerminationListener. But it is quite common and convenient that the container holding a component also acts as its listener. dbc@csit.fsu.edu

  23. Event Model Illustrated with Button Window with event source—a button. The button puts L on its action listener list. Instance of class implementing ActionListener L S L ActionEvent actionPerformed method Click here When user clicks the button, the button makes an ActionEvent object and passes it to the actionPerformed() method of listeners on its list. dbc@csit.fsu.edu

  24. Handling Events in the Button Panel class ButtonPanel extends JPanel implements ActionListener { public ButtonPanel { . . . redButton.addActionListener(this) ; blueButton.addActionListener(this) ; greenButton.addActionListener(this) ; } public void actionPerformed(ActionEvent evt) { . . . Deal with event according to source } } • It is crucial here that ActionListener is an interface. • If it had been a class type, we could never inherit from both JPanel and ActionListener. dbc@csit.fsu.edu

  25. Handling Events from Multiple Sources • Our ButtonPanel is now listener for three different sources of action events. • All three buttons will invoke the same event-handling method, which must be implemented to distinguish the cases, eg: public void actionPerformed(ActionEvent evt) { if(evt.getSource() == redButton) setBackGround(Color.red) ; else if(evt.getSource() == blueButton) setBackground(Color.blue) ; else if(evt.getSource() == greenButton) setBackground(Color.green) ; repaint() ; } • Note setBackground() and repaint() are relatively low-level graphics comands. dbc@csit.fsu.edu

  26. Completing ButtonTest • An instance of our ButtonPanel is created, and added to the content pane of the JFrame: public static void main(String [] args) { JFrame frame = new JFrame() ; frame.setTitle(“ButtonTest”) ; frame.setSize(450, 300) ; frame.addWindowListener(new TerminationListener()) ; frame.getContentPane().add(new ButtonPanel()) ; frame.show() ; } • Calling add(new ButtonPanel()) nests a ButtonPanel container inside the content pane container associated with the frame. Latter hasborder layout: can only directly hold a single component per “area”—here the central area. dbc@csit.fsu.edu

  27. Running ButtonTest dbc@csit.fsu.edu

  28. Running ButtonTest Click! dbc@csit.fsu.edu

  29. Running ButtonTest dbc@csit.fsu.edu

  30. Check Boxes and Radio Buttons • Check boxes and radio buttons are variations on the stateless, clickable button we have just seen. The new versions have a definite (and clearly displayed) internal state. This state is toggled by clicking them. • At any time, a check box is either selected, or not selected (checked or unchecked). Radio buttons come in groups, and only one member of the group can be selected at a time. “Switching on” a new member of the group causes its predecessor to automatically be “switched off”. • Like JButton, the associated JCheckBox andJRadioButtoncomponents generate an ActionEvent when they are clicked. If the buttons demand immediate action (not always the case) these events may be handled by action listeners. dbc@csit.fsu.edu

  31. Adding a Check Box to a Panel class CheckBoxPanel extends JPanel implements ActionListener { public CheckBoxPanel() { redButton = new JCheckBox(“Red”, false) ; // Initially unselected add(redButton) ; redButton.addActionListener(this) ; } public void actionPerformed(ActionEvent evt) { if (redButton.isSelected()) // Test if selected setBackground(Color.red) ; else // Otherwise, event setBackground(defaultColor) ; // deselected button repaint() ; } private JCheckBox redButton ; private Color defaultColor = getBackground() ; // Initialization } dbc@csit.fsu.edu

  32. Running CheckBoxTest dbc@csit.fsu.edu

  33. Running CheckBoxTest Click! dbc@csit.fsu.edu

  34. Running CheckBoxTest dbc@csit.fsu.edu

  35. Running CheckBoxTest Click! dbc@csit.fsu.edu

  36. Running CheckBoxTest dbc@csit.fsu.edu

  37. Adding a Radio Button Group to a Panel public RadioButtonPanel() { redButton = new JRadioButton(“Red”, true) ; // Initially selected blueButton = new JRadioButton(“Blue”, false) ; // Initially unselected greenButton = new JRadioButton(“Green”, false) ; // . . . . . . add(redButton) ; // Add all three buttons add(blueButton) ; // to the panel (for display) add(greenButton) ; redButton.addActionListener(this) ; blueButton.addActionListener(this) ; greenButton.addActionListener(this) ; ButtonGroup group = new ButtonGroup() ;// A group of buttons group.add(redButton) ; // Add all three buttons to group.add(blueButton) ; // the button group (for control) group.add(greenButton) ; setBackground(Color.red) ; } dbc@csit.fsu.edu

  38. Handling Radio Button Events • Note grouping radio buttons with ButtonGroupin no way affects their display. That is alayoutissue. The button group only ensures other buttons are switched off when a new one is switched on (separation of control and view). class RadioButtonPanel extends JPanel implements ActionListener { . . . Declaration of constructor (previous slide) . . . public void actionPerformed(ActionEvent evt) { if (redButton.isSelected()) // Test if selected setBackground(Color.red) ; if (blueButton.isSelected()) setBackground(Color.blue) ; if (greenButton.isSelected()) setBackground(Color.green) ; repaint() ; } private JRadioButton redButton, blueButton, greenButton ; } dbc@csit.fsu.edu

  39. Running RadioButtonTest dbc@csit.fsu.edu

  40. Running RadioButtonTest Click! dbc@csit.fsu.edu

  41. Running RadioButtonTest dbc@csit.fsu.edu

  42. Model-view-controller Design Pattern • Swing components are considered to have three aspects: • Contents, e.g., the state of a button, text string in a text field. • Visual appearance, e.g., colour, size and shape of a button. • Behavior, e.g, response to events such as mouse clicks. • Swing attempts to keep these aspects separate—it tries to follow a model-view-controller design pattern, as far as practical. • In practice the interaction between behavior and visual appearance usually needs to be quite strongly coupled, e.g. to meet the requirements of a custom look and feel. • However Swing components do normally provide well-defined, well-separated, model classes. dbc@csit.fsu.edu

  43. The ButtonModel Interface • Used for simple buttons, check boxes and radio buttons—their getModel() methods will return an object (actually an instance of DefaultButtonModel) that presents interface: public interface ButtonModel extends ItemSelectable { String getActionCommand() ; int getMnemonic() ; . . . boolean isSelected() ; boolen isArmed() ; boolean isEnabled() ; boolean isPressed() ; . . . void addActionListener(ActionListener l) . . . } dbc@csit.fsu.edu

  44. The Text Field Component • A text field is a component used for inputting a small amount of text—it only accepts a single line. It automatically takes care of normal line-editing, as determined by whatever look-and-feel is in effect. • The associated class is JTextField. • For larger amounts of text you should use a text area. • A text field might also be used for displaying a short amount of text—not allowing editing. • The model associated with a text field (or a text area) is a, document model, implementing DocumentModel. • For these components, listeners are usually added to the model, rather than the component itself. dbc@csit.fsu.edu

  45. Document Listeners • The DocumentListener interface has three event handling methods: interface DocumentListener extends EventListener { void insertUpdate(DocumentEvent evt) ; void removeUpdate(DocumentEvent evt) ; void changedUpdate(DocumentEvent evt) ; } • Insert and remove updates have straightforward meaning. Changed updates not generated by the plain documents we discuss (but by style documents with embedded formatting). • In simple cases may not care which method was invoked—may simply reread whole string from field every time it is updated. • Note this interface is in javax.swing.event (notjava.awt.event) dbc@csit.fsu.edu

  46. Adding Two Text Fields to a Panel class TextFieldPanel extends JPanel implements DocumentListener { public TextFieldPanel() { input = new JTextField(20) ; // Preferred width in columns. input.getDocument().addDocumentListener(this) ; add(input) ; display = new JTextField(20) ; // Displays current input text display.setEditable(false) ; // Editing disabled for this field. add(display) ; } public void insertUpdate(DocumentEvent evt) { display.setText(input.getText()) ; // Copy from input field to display } public void removeUpdate(DocumentEvent evt) { display.setText(input.getText()) ; // Copy from input field to display } public void changedUpdate(DocumentEvent evt) {} private JTextField field, display ; } dbc@csit.fsu.edu

  47. Running TextFieldTest dbc@csit.fsu.edu

  48. Running TextFieldTest Type! dbc@csit.fsu.edu

  49. Running TextFieldTest dbc@csit.fsu.edu

  50. Dialog Boxes • Buttons and text fields allow input from the user. But they cannotforce the user to do anything. The program simply reacts to whatever component the user is focused on. • Sometimes you need to insist the user makes a choice before anything else can proceed. • Scenario: • The user clicks a button to change something in the display (e.g. an entry in a list). At that point you need to enter into a dialog with the user to establish exactly what is required, before user’s attention goes elsewhere. • Following example illustrates a new way of getting text input from user. User clicks change button, then is prompted with a dialog box. dbc@csit.fsu.edu

More Related