Presentation is loading. Please wait.

Presentation is loading. Please wait.

Y. Daniel Liang 1 Graphical User Interfaces Chapter 12.

Similar presentations


Presentation on theme: "Y. Daniel Liang 1 Graphical User Interfaces Chapter 12."— Presentation transcript:

1 Y. Daniel Liang 1 Graphical User Interfaces Chapter 12

2 Y. Daniel Liang 2 Programs MyFrame MyFrameWithComponents CenterFrame ShowFlowLayout ShowGridLayout TestPanels SimpleEventsDemo Two classes within one file SimpleEvent DemoAnonymousInnerClass

3 Y. Daniel Liang 3 Programs ShowInnerClass GuiNew See the object code for the inner classes TestActionEvent Team 4 TestActionEventNew Team4 ButtonDemo ViewFile Team 3 signature.txt CreateMenus Team # 1 and 2 new.gif and open.gif

4 Y. Daniel Liang 4 Programs TestPanel Team #5 GuiNew See the object code for the inner classes TestActionEvent Team 4 TestActionEventNew Team4 ButtonDemo ViewFile Team 3 signature.txt CreateMenus Team # 1 and 2 new.gif and open.gif

5 Y. Daniel Liang 5 Graphical User Interfaces -- Introduction F Users have become accustomed to using a graphical user interface (GUI) through which they interact with a program  Java provides strong support for building GUIs through the java.awt and javax.swing packages F This section focuses on: –GUI components –event-driven programming –containers and component hierarchies –layout managers

6 Y. Daniel Liang 6 GUI Elements F The key elements of a Java graphical user interface are: –GUI components –layout managers –event processing F GUI components, such as text fields and buttons, are the screen elements that a user manipulates with the mouse and keyboard F Layout managers govern how the components appear on the screen F Events signal important user actions, like a mouse click

7 Y. Daniel Liang 7 Swing Graphic User Interfaces (GUI) Objectives: F See GUI Components F Create user interfaces using frames, panels, and plain GUI components  Understand the role of layout managers  To use the FlowLayout, GridLayout, and BorderLayout managers F To use JPanels as subcontainers

8 Y. Daniel Liang 8 Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your name: " JLabel jlblName = new JLabel("Enter your name: "); // Create a text field with text "Type Name Here" JTextField jtfName = new JTextField("Type Name Here"); // Create a check box with text bold JCheckBox jchkBold = new JCheckBox("Bold"); // Create a radio button with text red JRadioButton jrbRed = new JRadioButton("Red"); // Create a combo box with choices red, green, and blue JComboBox jcboColor = new JComboBox(new String[]{"Red", "Green", "Blue"}); Button LabelText field Check Box Radio Button Combo Box

9 Y. Daniel Liang 9 GUI Components F //Create a button with text hello JButton jbtHello = new JButton(“Hello ”); F //Create a label with text “Enter your age: “); JLabel jlblAge = new JLabel(“Enter your age: “); F //Create a text field with text “Type age here: “ JTextField jtfAge = new JTextField (“Type age here: “);

10 Y. Daniel Liang 10 GUI Components F //Create a check box with text bold JCheckBox jchkBold = new JCheckBox(“Bold”); F //Create a radio button with text blue JRadioButton jrbBlue = new JRadioButton(“Blue”); F //Create a combo box with options red, green, and blue JComboBox jcoColor = new JComboBox(new String[] {“Red”, “Green”, “Blue”});

11 Y. Daniel Liang 11 Swing versus AWT F First GUI classes were bundled in a library known as Abstract Windows Toolkit (AWT) Heavy weight components -AWT components F Platform-specifics- more error-prone F A peer-based approach relies heavily on the underlying platform (operating system) F Will slowly fade away- not recommended for new applications

12 Y. Daniel Liang 12 Light Weight Components -Swing F Less dependent on the target platform F Uses less of the native GUI resources F Replaced AWT components with a more robust, versatile, and flexible library known as Swing components F Swing components are painted directly on canvas using Java code except for components that are subclasses of java.awt.Window or java.awt.Panel, which must be drawn using native GUI on a specific platform

13 Y. Daniel Liang 13 Swing GUI Components contd The name of Swing components are prefixed with a J Examples: F JButton F JLabel F JTextField F JCheckBox F JRadioButton F JComboBox These are subclasses of JComponent

14 Y. Daniel Liang 14 Swing GUI Classes Classified Into Three Groups F Container classes F Helper Classes F Component Classes

15 Y. Daniel Liang 15 Containers Component Container Window Panel Dialog Frame Applet JComponent (Base for Swing Components) JApplet JFrame JDialog

16 Y. Daniel Liang 16 Swing GUI Container Classes Container classes: F JFrame F JPanel F JApplet -Subclasses of Component -Used to contains other components -Uses Layout managers to position and place components in a container in the desired location

17 Y. Daniel Liang 17 Helper Classes F Graphics F Color F Font F FontMetrics F Dimension F Layout Manager -Not subclasses of Component -Used by components and containers to draw and place objects -The helper classes are in the java.awt packages

18 Y. Daniel Liang 18 Frames To create a user interface (UI), you need to create either a frame or an applet to hold the user-interface components For Swing GUI programs, use JFrame class to create windows.

19 Y. Daniel Liang 19 Creating Frames Run import javax.swing.*; public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } MyFrame

20 Y. Daniel Liang 20 Content Pane of A Frame A frame’s content pane is the section of the frame that excludes the title and menu bars and the border The content pane is used to display the text images, etc.

21 Y. Daniel Liang 21 Add Components to a Frame contd. JDK 1.5 allows you to place components to the content pane by invoking a frame's add() method. This new feature is called content pane delegation. Strictly speaking, a component is added into the content pane of a frame. But for simplicity, we say that a component is added to the frame.

22 Y. Daniel Liang 22 Content Pane Delegation in JDK 1.5 // Add a button into the frame frame.getContentPane().add( new JButton("OK")); Run MyFrameWithComponents Title bar Content pane // Add a button into the frame JButton jbtOK = new JButton("OK"); frame.add(jbtOK);

23 Y. Daniel Liang 23 JFrame Class

24 Y. Daniel Liang 24 Center a Frame Run CenterFrame.java

25 Y. Daniel Liang 25 Layout Managers F Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems. F The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container. F Layout managers are set in containers using the setLayout(LayoutManager) method in a container.

26 Y. Daniel Liang 26 Layout Managers  There are five predefined layout managers in the java.awt package: –flow layout –border layout –card layout –grid layout –grid bag layout F Each container has a particular layout manager associated with it by default F A programmer can also create custom layout managers

27 Y. Daniel Liang 27 Three Simple and Useful Layout Managers F FlowLayout F GridLayout F BorderLayout Each is an interface –whose instances specify how components are arranged in a container

28 Y. Daniel Liang 28 Layout Manager -FlowLayout 1 2 3 45 6

29 Y. Daniel Liang 29 The FlowLayout Class

30 Y. Daniel Liang 30 Layout Managers (FlowLayout) Provides a level of abstraction that automatically maps your user interface on all windows systems Provides platform independence The FlowLayout manager arranges the components in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started. Run ShowFlowLayout.java

31 Y. Daniel Liang 31 FlowLayout Another ExampleStopped Here mon, 6/22/09 Write a program that adds three labels and text fields into the content pane of a frame with a FlowLayout manager. ShowFlowLayoutNewRun

32 Y. Daniel Liang 32 The ShowFlowLayoutNew.java See the program. It is the preferred style of creating GUI applications for these three reasons: 1.Creating a GUI application means creating a frame, so it is natural to define a frame to extend JFrame. 2. The frame may be further extended to add new components or functions 3. The class can be easily reused. For example, you can create multiple frames by creating multiple instances of the class

33 Y. Daniel Liang 33 The ShowFlowLayoutNew.java contd. Using one style consistently makes programs easy to read and maintain. 1.From now on, most of the GUI main classes will extend the JFrame class. 2. The constructor of the main class will construct the user interface. 3.The main method will create an instance of the main class and then display the frame 4. Use a layout manager to place components in a frame.

34 Y. Daniel Liang 34 Layout Management Classes Container JPanel “Interface” Layout Manager GridLayout To set a layout manager, pick the appropriate layout manager class and add it to the container: JPanel panel = new JPanel (); panel.setLayout(new GridLayout(4,3)); // 4 rows and 3 //columns

35 Y. Daniel Liang 35 Layout Manager -GridLayout 12 3 45 6 78 9 1011 12

36 Y. Daniel Liang 36 Layout Manager (GridLayout) The GridLayout manager arranges the components in the container into the cells of a grid. The components are placed in the grid from left to right, row by row. Run ShowGridLayout.java

37 Y. Daniel Liang 37 GridLayout Example Rewrite the program in the preceding example using a GridLayout manager instead of a FlowLayout manager to display the labels and text fields. ShowGridLayoutNewRun

38 Y. Daniel Liang 38 The GridLayout Class

39 Y. Daniel Liang 39 Layout Manager -BorderLayout NORTH WESTCENTEREAST SOUTH

40 Y. Daniel Liang 40 Layout Manager (BorderLayout) The BorderLayout manager divides the window into five areas: East, South, West, North, and Center. You can place one (or no components) in an area. The order in which the components are placed is not important, because you always tell the container in which area a component is placed.

41 Y. Daniel Liang 41 BorderLayout Example ShowBorderLayoutRun

42 Y. Daniel Liang 42 The BorderLayout Class

43 Y. Daniel Liang 43 GridBag Layout F Designed as a two-dimensional grid of columns and rows F However, not all cells in the grid are the same size F Components may span multiple columns and rows  Each component in a grid bag layout is associated with a set of constraints, defined by the GridBagConstraints class F A grid bag layout is the most versatile, and most complex, of the predefined layout managers

44 Y. Daniel Liang 44 Use Panels as Subcontainers You can divide a window into panels. Panels act as subcontainers to group user –interface components Can add the buttons in one panel, and then add the panel into the frame. JPanel is the swing version of Panel

45 Y. Daniel Liang 45 Use Panels as Subcontainers contd. new JPanel () will create a panel with a default FlowLayout manager OR new JPanel (LayoutManager) to create a panel with the specified layout manager Use the add (Component) method to add a component to the panel

46 Y. Daniel Liang 46 Use Panels as Containers The following code creates a panel and adds a button to it: JPanel panel2 = new JPanel(); panel2.add(new JButton(“OK”)); By default, JPanel uses the FlowLayout. manager Panels can be placed inside a frame or inside another panel. The following statement places panel panel2 into frame frame2: Frame2.add(panel2);

47 Y. Daniel Liang 47 Use Panels as Containers Note: To add a component to JFrame, you actually add it to the content pane of JFrame. Prior to JDK 1.4 frame.getContentPane().add(new JButton("OK")); See program : MyFrameWithComponents. To add a component to a panel, you add it directly to the panel using the add method.

48 Y. Daniel Liang 48 Testing Panels Example This example uses panels to organize components. The program creates a user interface for a Microwave oven. TestPanelsRun

49 Y. Daniel Liang 49 Use Panels as Subcontainers JPanel class can be used for drawing graphics, displaying text, and viewing images. Although you may draw things directly on a frame or an applet, it is recommended that you contain your drawings in a canvas, so that they do not interfere with other components. SKIP

50 Y. Daniel Liang 50 Common Features of Swing Components

51 Y. Daniel Liang 51 Chapter 14

52 Y. Daniel Liang 52 Programs TestActionEvent TestWindowEvent TestMultipleListener ShowInnerClass SimpleEventDemoInnerClass SimpleEventDemo Anonymous??? InnerClass????

53 Y. Daniel Liang 53 Objectives To start with event-driven programming with a simple example (§14.1). To explain the concept of event-driven programming (§14.2). To understand events, event sources, and event classes (§14.2). To declare listener classes and write the code to handle events (§14.3). To register listener objects in the source object (§14.3). To understand how an event is handled (§14.3). To write programs to deal with ActionEvent (§14.3).

54 Y. Daniel Liang 54 Event Driven Programming F All the programs that we have written were object-oriented programs that executed in a procedural order. F We used decision and loop statements to control the flow of execution. The program, itself, dictated the flow of execution

55 Y. Daniel Liang 55 Event Driven Programming F Java graphic programming is event driven. F Codes are executed when an event occurs – An event is defined as a signal to the program that something has occurred. For example, click a button, close a window, or move a mouse, press a key on the keyboard, and so on

56 Y. Daniel Liang 56 Taste of Event-Driven Programming F The example displays a button in the frame. A message is displayed on the console when a button is clicked. SimpleEventDemo Run

57 Y. Daniel Liang 57 Events F An event can be defined as a type of signal to the program that something has happened. F The event is generated by external user actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, such as a timer. F The component on which an event is fired or generated is called the source object.

58 Y. Daniel Liang 58 Event Classes An event is an object of the EventObject class.

59 Y. Daniel Liang 59 User ActionSource ObjectEvent Type (Event Class) Generated Click a buttonJButtonAction Event Change TextJTextComponentTextEvent Press return on a text field JTextFieldAction Event Select a new itemJComboBoxItemEvent ActionEvent Select items(s)JListListSelectionEvent Click a check boxJCheckBoxItemEvent ActionEvent Click a radio buttonJRadioButtonItemEvent ActionEvent Select a menu itemJMenuItemAction Event Window opened, closed, iconified, deiconified, or closing WindowWindowEvent

60 Y. Daniel Liang 60 Event Information An event object contains whatever properties are pertinent to the event. You can identify the source object of the event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as button actions, window events, component events, mouse movements, and keystrokes. Table 14.1 lists external user actions, source objects, and event types generated.

61 Y. Daniel Liang 61 Table 14.1 Selected User Actions Stop here wed, 6/24/09 SourceEvent Type User ActionObjectGenerated Click a button JButtonActionEvent Click a check box JCheckBoxItemEvent, ActionEvent Click a radio button JRadioButtonItemEvent, ActionEvent Press return on a text field JTextFieldActionEvent Select a new item JComboBoxItemEvent, ActionEvent Window opened, closed, etc. WindowWindowEvent Mouse pressed, released, etc. ComponentMouseEvent Key released, pressed, etc. ComponentKeyEvent

62 Y. Daniel Liang 62 Event Class Listener InterfaceListener Method (Handler) ActionEvent ActionListener actionPerformed(ActionEvent e) ItemEvent ItemListeneritemStateChange(ItemEvent e) WindowEventWindowListenerwindowClosing(WindowEvent e) windowOpened(WindowEvent e) windowIconified(WindowEvent e) windowDeiconified(WindowEvent e) windowClosed(WindowEvent e) windowActivated(WindowEvent e) windowDeactivated(WindowEvent e)

63 Y. Daniel Liang 63 Iconifying means to substitute a small icon on the desktop for the window Deiconfying means just the opposite

64 Y. Daniel Liang 64 Inner Class Listeners A listener class is designed specifically to create a listener object for a GUI component (e.g., a button). It will not be shared by other applications. So, it is appropriate to define the listener class inside the frame class as an inner class.

65 Y. Daniel Liang 65 Inner Classes Inner class: A class is a member of another class. Advantages: In some applications, you can use an inner class to make programs simple. F An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class. ShowInnerClass

66 Y. Daniel Liang 66 Inner ClassesRun OuterClass.java, cont.

67 Y. Daniel Liang 67 Inner Classes (cont.) F Inner classes can make programs simple and concise. F An inner class supports the work of its containing outer class and is compiled into a class named OuterClassName$InnerClassName.class. F For example, the inner class InnerClass in OuterClass is compiled into OuterClass$InnerClass.class.

68 Y. Daniel Liang 68 Inner Classes (cont.) F An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class. F An inner class can be declared static. A static inner class can be accessed using the outer class name. A static inner class cannot access nonstatic members of the outer class

69 Y. Daniel Liang 69 Revising SimpleEventDemo Using Inner Classes SimpleEventDemoInnerClass Run

70 Y. Daniel Liang 70 Anonymous Inner Classes F An anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit extends or implements clause. F An anonymous inner class must implement all the abstract methods in the superclass or in the interface.  An anonymous inner class always uses the no-arg constructor from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object(). F An anonymous inner class is compiled into a class named OuterClassName$n.class. For example, if the outer class Test has two anonymous inner classes, these two classes are compiled into Test$1.class and Test$2.class.

71 Y. Daniel Liang 71 Anonymous Inner Classes (cont.) Inner class listeners can be shortened using anonymous inner classes. An anonymous inner class is an inner class without a name. It combines declaring an inner class and creating an instance of the class in one step. An anonymous inner class is declared as follows: new SuperClassName/InterfaceName() { // Implement or override methods in superclass or interface // Other methods if necessary }

72 Y. Daniel Liang 72 Anonymous Inner Classes (cont.) public class SimpleEvent DemoAnonymousInnerClass extends Jframe{ public SimpleEvent DemoAnonymousInnerClass () { JButton jbtOK = new JButton (“OK”); Set Layout (new FlowLayout()); add (jbtOK); // Create and register anonymous inner class listener jbtOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("It is OK"); } }); }

73 Y. Daniel Liang 73 Revising SimpleEventDemo Using Anonymous Inner Classes SimpleEventDemoAnonymousInnerClass Run

74 Y. Daniel Liang 74 Example: Handling Simple Action Events F Objective: Display two buttons OK and Cancel in the window. A message is displayed on the console to indicate which button is clicked, when a button is clicked. TestActionEvent Run

75 Y. Daniel Liang 75 Interaction Between Source and Listener 1.jbtOK registers btListener by invoking addActionListener(btListner). 2.jbtCancel registers btListener by invoking addActionListener(btListner). 3.jbtOK invokes btListener’s actionPerformed method to process an ActionEvnet. 4.jbtCancel invokes btListener’s actionPerformed method to process an ActionEvent.

76 Y. Daniel Liang 76 Example: Handling Window Events TestWindowEvent Run  Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event.

77 Y. Daniel Liang 77 Example: Multiple Listeners for a Single Source TestMultipleListener Run F Objective: This example modifies Listing 14.1 to add a new listener for each button. The two buttons OK and Cancel use the frame class as the listener. This example creates a new listener class as an additional listener for the action events on the buttons. When a button is clicked, both listeners respond to the action event.

78 Y. Daniel Liang 78 Event-Driven Programming Steps to design and implement a GUI: 1. Identify the actions (methods) that your program needs to perform -withdraw funds from savings account 2. Identify each input that is needed for the action – withdrawal amount 3. Identify the outputs that you must display for each action – the current amount 4. Supply the user interface components – buttons for action text fields to hold input labels for output

79 Y. Daniel Liang 79 Event-Driven Programming Steps to design and implement a GUI continued: 5. Include the event handler class – -for each button, add an object of a listener class -the listener classes must implement the ActionListener interface -Place commands for the action in the actionPerformed method class AddInterestListener implements ActionListener { public void actionPerformed (ActionEvent event){ //appropriate button action is placed here }

80 Y. Daniel Liang 80 Event-Driven Programming Steps to design and implement a GUI continued: 6. Include listener objects and attach them to the event sources ActionListener listener = new AddInterestListener(); button.addActionListener(listener); 7. Choose a layout manager

81 Y. Daniel Liang 81 Event-Driven Programming F Programs with GUIs must respond to events, generated by GUI components, that indicate that specific actions have occurred F A special category of classes, called listeners, wait for events to occur F Therefore, a GUI program is composed of: –the code that presents the GUI to the user –the listeners that wait for events to occur –the specific code that is executed when events occur

82 Y. Daniel Liang 82 Event-Driven Programming F There is a listener interface defined for each event type F Each listener interface contains the abstract methods required to respond to specific events F A listener class implements a particular listener interface F Listeners are "added" to a particular GUI component F When a component generates an event, the method corresponding to that event is executed in the listener

83 Y. Daniel Liang 83 Handling Events Run TestActionEvent

84 Y. Daniel Liang 84 Event Interfaces F Multiple listeners can be added to a component F Multiple components can be processed by the same listener F Furthermore, one listener class can implement multiple listener interfaces F Therefore one class can listen for many types of events F Run program TestMultipleListner

85 Y. Daniel Liang 85 The GUI Program Model Listeners Program- specific GUI Event effects Add listeners Handle events

86 Y. Daniel Liang 86 User action Source Object Register a listener object Trigger an event Event Object Generate An event Listener Object Event Handler Notify Listener Event Registration, Listening, and Handling An event is triggered by the user actions on the source object The source object generates the event object and invokes the handle of the listener object to process the event

87 Y. Daniel Liang 87 JButton A button is a component that triggers an action event when clicked. The following are JButton non-default constructors: JButton(String text) JButton(String text, Icon icon) JButton(Icon icon)

88 Y. Daniel Liang 88 Responding to JButton Events public void actionPerformed(ActionEvent e) { // Get the button label String actionCommand = e.getActionCommand(); // Make sure the event source is a button if (e.getSource() instanceof JButton) // Make sure it is the right button if ("My Button".equals(actionCommand) System.out.println ("Button pressed!"); }

89 Y. Daniel Liang 89 JButton RunButtonDemo Run ButtonDemo.java

90 Y. Daniel Liang 90 JLabel A label is a display area for a short text, an image, or both. F A label defines a line of text displayed on a GUI F Labels are static in the sense that they cannot be selected or modified by the human user once added to a container  A label is instantiated from the Label class  The Label class contains several constructors and methods for setting up and modifying a label's content and alignment

91 Y. Daniel Liang 91 JText Field F Most graphical programs collect text input through text fields. A text field displays a single line of text in a GUI F Text fields are useful in that they enable the user to enter in variable data (such as a name or a description).

92 Y. Daniel Liang 92 JTextField The text field is defined by the JTextField class. When you construct the text field, you need to supply the width – the estimated number of characters entered by the user. final int FIELD_WIDTH = 12; //constant final JTextField rateField = new JTextField(FIELD_WIDTH); You need to label each text field: JLabel rateLabel = new JLabel(“Interest Rate: “); Run InvestViewer.java (BankAccount.java)

93 Y. Daniel Liang 93 JTextField Methods F getText() Returns the string from the text field. F setText(String text) Puts the given string in the text field. F setEditable(boolean editable) Enables or disables the text field to be edited. By default, editable is true. F setColumns(int) Sets the number of columns in this text field. The length of the text field is changeable.

94 Y. Daniel Liang 94 JTextArea F A text area is similar to a TextField, but permits the user to enter multiple lines of text  It is defined by the J TextArea classes F A text area automatically has scrollbars on its bottom and right sides Run ViewFile.java

95 Y. Daniel Liang 95 JTextArea If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines of text.

96 Y. Daniel Liang 96 JComboBox A combo box is a simple list of items from which the user can choose. It performs basically the same function as a list, but can get only one value. To create a choice, use its default constructor: JComboBox()

97 Y. Daniel Liang 97 JComboBox Methods To add an item to a JComboBox jcbo, use jcbo.addItem(Object item) To get an item from JComboBox jcbo, use jcbo.getItem()

98 Y. Daniel Liang 98 JCheckBox A check box is a component that enables the user to toggle a choice on or off, like a light switch.

99 Y. Daniel Liang 99 JRadioButton Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.

100 Y. Daniel Liang 100 JRadioButton Properties JRadioButton has all the properties in JButton. Additionally, JButton has the following property: selected

101 Y. Daniel Liang 101 Grouping Radio Buttons ButtonGroup btg = new ButtonGroup(); btg.add(jrb1); btg.add(jrb2);

102 Y. Daniel Liang 102 Example 11.8: Using Radio Buttons This example shows a program that simulates traffic lights. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time. No light is on when the program starts. RunRadioButtonDemo

103 Y. Daniel Liang 103 JOptionPane Dialogs F A dialog is normally used as a temporary window to receive additional information from the user, or to provide notification that some event has occurred.

104 Y. Daniel Liang 104 Message Dialogs A message dialog box simply displays a message to alert the user and waits for the user to click the OK button to close the dialog. icon message button

105 Y. Daniel Liang 105 Message Types (5) The messageType is one of the following constants: JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.PLAIN_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE

106 Y. Daniel Liang 106 Message Types, cont.

107 Y. Daniel Liang 107 Confirmation Dialogs A message dialog box displays a message and waits for the user to click the OK button to dismiss the dialog. The message dialog does not return any value. A confirmation dialog asks a question and requires the user to respond with an appropriate button. The confirmation dialog returns a value that corresponds to a selected button.

108 Y. Daniel Liang 108 Input Dialogs An input dialog box is used to receive input from the user. The input can be entered from a text field or selected from a combo box or a list. Selectable values can be specified in an array, and a particular value can be designated as the initial selected value.

109 Y. Daniel Liang 109 Option Dialogs An option dialog allows you to create custom buttons.

110 Y. Daniel Liang 110 Example: Creating Standard Dialogs  Objective: This example demonstrates using standard dialogs. The program prompts the user to select the annual interest rate from a list in an input dialog, the number of years from a combo box in an input dialog, and the loan amount from an input dialog, and displays the loan payment schedule in a text area inside a JScrollPane in a messasge dialog.

111 Y. Daniel Liang 111 Example: Creating Standard Dialogs, cont. Run JOptionPaneDemo (Mortgage.java)

112 Y. Daniel Liang 112 Menus F make selections easier F are widely used in windows applications

113 Y. Daniel Liang 113 Menus JComponent JMenuBar AbstractButton JPopupMenu JMenuItem JRadioButtonMenuItem JMenu JCheckBoxMenuItem

114 Y. Daniel Liang 114 Menus Java provides several classes—to implement menus in a frame F JMenuBar – the top-level container used to hold menus  JMenu the menu bar itself -It may hold submenus  JMenuItem has no further submenus The user can select (or toggle on or off) to make a selection

115 Y. Daniel Liang 115 Menus JMenuItem Contd. The menu item can be an instance of: F JMenuItem F JCheckBoxMenuItem F JRadioButtonMenuItem When the user selects a menu item, the menu item sends an action event. Therefore, you should add a listener to each menu item. jmenuItemExit.addListener(listener);

116 Y. Daniel Liang 116 Menus Classes contd. F JCheckBoxMenuItem permits you to check or uncheck a menu item same as a checkbox F JRadioButtonMenuItem permits you to choose between mutually exclusive menus F A JFrame or JApplet can hold a menu bar to which the pull-down menus are attached. Menus consist of menu items that the user can select (or toggle on or off). Menu bars can be viewed as a structure to support menus.

117 Y. Daniel Liang 117 CreateMenus

118 Y. Daniel Liang 118 CreateMenus

119 Y. Daniel Liang 119 Create Menus

120 Y. Daniel Liang 120 Create Menu Submenu

121 Y. Daniel Liang 121 Menus F Run Program: CreateMenus F Need Inputs: new.gif and open.gif F

122 Y. Daniel Liang 122 Run Gui.java Swap text Clear Screen Enter text

123 Y. Daniel Liang 123 The JMenuBar Class JFrame f = new JFrame(); f.setSize(300, 200); f.setVisible(true); JMenuBar mb = new JMenuBar(); f.setJMenuBar(mb); A menu bar holds menus; the menu bar can only be added to a frame. Following is the code to create and add a JMenuBar to a frame:

124 Y. Daniel Liang 124 The Menu Class JMenu fileMenu = new JMenu("File", false); JMenu helpMenu = new JMenu("Help", true); mb.add(fileMenu); mb.add(helpMenu); You attach menus onto a JMenuBar. The following code creates two menus, File and Help, and adds them to the JMenuBar mb :

125 Y. Daniel Liang 125 The JMenuItem Class fileMenu.add(new JMenuItem("new")); fileMenu.add(new JMenuItem("open")); fileMenu.add(new JMenuItem("-")); fileMenu.add(new JMenuItem("print")); fileMenu.add(new JMenuItem("exit")); fileMenu.add(new JMenuItem("-")); You add menu items on a menu. The following code adds menu items and item separators in menu fileMenu :

126 Y. Daniel Liang 126 Submenus JMenu softwareHelpSubMenu = new JMenu("Software"); JMenu hardwareHelpSubMenu = new JMenu("Hardware"); helpMenu.add(softwareHelpSubMenu); helpMenu.add(hardwareHelpSubMenu); softwareHelpSubMenu.add(new JMenuItem("Unix")); softwareHelpSubMenu.add(new JMenuItem("NT")); softwareHelpSubMenu.add(new JMenuItem(“Vista")); You can add submenus into menu items. The following code adds the submenus “Unix,” “NT,” and “Vista” into the menu item “Software.”

127 Y. Daniel Liang 127 JScrollBar  A scroll bar is a control that enables the user to select from a range of values. The scrollbar appears in two styles: horizontal and vertical.

128 Y. Daniel Liang 128 Example 11.13: Using Scrollbars This example uses horizontal and vertical scrollbars to control a message displayed on a panel. The horizontal scrollbar is used to move the message to the left or the right, and the vertical scrollbar to move it up and down. ScrollBarDemo (MessagePanel) Run

129 Y. Daniel Liang 129 JScrollPane  A scroll pane is a component that supports automatically scrolling without coding.


Download ppt "Y. Daniel Liang 1 Graphical User Interfaces Chapter 12."

Similar presentations


Ads by Google