* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Slides 05
Survey
Document related concepts
C Sharp syntax wikipedia , lookup
Abstraction (computer science) wikipedia , lookup
Logic programming wikipedia , lookup
Java syntax wikipedia , lookup
Programming language wikipedia , lookup
Falcon (programming language) wikipedia , lookup
Go (programming language) wikipedia , lookup
Functional programming wikipedia , lookup
Reactive programming wikipedia , lookup
Scala (programming language) wikipedia , lookup
Aqua (user interface) wikipedia , lookup
Object-oriented programming wikipedia , lookup
Structured programming wikipedia , lookup
Java (programming language) wikipedia , lookup
Transcript
Java Programming Week 5: Graphical User Interfaces (Chapter 18) Chapter Goals • To understand the use of layout managers to arrange user-interface components in a container • To become familiar with common user-interface components, such as buttons, combo boxes, text areas, and menus • To build programs that handle events from userinterface components • To learn how to browse the Java documentation COIT11134 - Java Programming 2 GUI Terminologies A GUI – Interactive Input /Output via a GUI A GUI consists of: What user sees on the screen (buttons, menus, combo box etc.) The code to process user actions (what to do when the buttons are clicked etc) COIT11134 - Java Programming 3 GUI Terminologies (cont.) Components form a GUI In Java, components are predefined in java.awt and javax.swing packages In swing library: JButton, JTextField, JTextArea, JLable, JRadioButton, JFrame etc. A Java GUI is a frame COIT11134 - Java Programming 4 GUI Terminologies (cont.) Frame hold panels and other components Panel can hold panels Panel can hold other components COIT11134 - Java Programming 5 Layout Management • Up to now, we have had limited control over layout of components • When we used a panel, it arranged the components from the left to the right • User-interface components are arranged by placing them inside containers • Containers can be placed inside larger containers • Each container has a layout manager that directs the arrangement of its components COIT11134 - Java Programming 6 Layout Management • Three useful layout managers: border layout flow layout grid layout • By default, JPanel places components from left to right and starts a new row when needed • Panel layout carried out by FlowLayout layout manager • Can set other layout managers panel.setLayout(new BorderLayout()); COIT11134 - Java Programming 7 Border Layout • Border layout groups container into five areas: center, north, west, south and east COIT11134 - Java Programming 8 Border Layout • Default layout manager for a frame (technically, the frame's content pane) • When adding a component, specify the position like this: panel.add(component, BorderLayout.NORTH); • Expands each component to fill the entire allotted area • If that is not desirable, place each component inside a panel COIT11134 - Java Programming 9 Grid Layout • Arranges components in a grid with a fixed number of rows and columns • Resizes each component so that they all have same size • Expands each component to fill the entire allotted area • Add the components, row by row, left to right: JPanel numberPanel = new JPanel(); numberPanel.setLayout(new GridLayout(4, 3)); numberPanel.add(button7); numberPanel.add(button8); numberPanel.add(button9); numberPanel.add(button4); . . . COIT11134 - Java Programming Continued 10 Grid Layout COIT11134 - Java Programming 11 Grid Bag Layout • Tabular arrangement of components • Columns can have different sizes • Components can span multiple columns • Quite complex to use • Not covered in the book • Fortunately, you can create acceptable-looking layouts by nesting panels • Give each panel an appropriate layout manager • Panels don't have visible borders • Use as many panels as needed to organize components COIT11134 - Java Programming 12 Nesting Panels Example Keypad from the ATM GUI in Chapter 12: JPanel keypadPanel = new JPanel(); keypadPanel.setLayout(new BorderLayout()); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); buttonPanel.add(button7); buttonPanel.add(button8); // . . . keypadPanel.add(buttonPanel, BorderLayout.CENTER); JTextField display = new JTextField(); keypadPanel.add(display, BorderLayout.NORTH); COIT11134 - Java Programming Continued 13 Nesting Panels Example (cont.) COIT11134 - Java Programming 14 Self Check 18.1 How do you add two buttons to the north area of a frame? Answer: First add them to a panel, then add the panel to the north end of a frame. COIT11134 - Java Programming 15 Self Check 18.2 How can you stack three buttons on top of each other? Button 1 Button 2 Button 3 Answer: Place them inside a panel with a GridLayout that has three rows and one column. COIT11134 - Java Programming 16 Choices • Radio buttons • Check boxes • Combo boxes COIT11134 - Java Programming 17 Radio Buttons • For a small set of mutually exclusive choices, use radio buttons or a combo box • In a radio button set, only one button can be selected at a time • When a button is selected, previously selected button in set is automatically turned off COIT11134 - Java Programming Continued 18 Radio Buttons (cont.) • In previous figure, font sizes are mutually exclusive: JRadioButton smallButton = new JRadioButton("Small"); JRadioButton mediumButton = new JRadioButton("Medium"); JRadioButton largeButton = new JRadioButton("Large"); // Add radio buttons into a ButtonGroup so that // only one button in group is on at any time ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton); COIT11134 - Java Programming 19 Radio Buttons • Button group does not place buttons close to each other on container • It is your job to arrange buttons on screen • isSelected: called to find out if a button is currently selected or not if(largeButton.isSelected()) size = LARGE_SIZE • Call setSelected(true) on a radio button in group before making the enclosing frame visible COIT11134 - Java Programming 20 Borders • Place a border around a panel to group its contents visually • EtchedBorder: three-dimensional etched effect • Can add a border to any component, but most commonly to panels: JPanel panel = new JPanel(); panel.setBorder(new EtchedBorder()); • TitledBorder: a border with a title panel.setBorder(new TitledBorder(new EtchedBorder(), "Size")); COIT11134 - Java Programming 21 Check Boxes • Two states: checked and unchecked • Use one checkbox for a binary choice • Use a group of check boxes when one selection does not exclude another • Example: "bold" and "italic" in previous figure • Construct by giving the name in the constructor: JCheckBox italicCheckBox = new JCheckBox("Italic"); • Don't place into a button group COIT11134 - Java Programming 22 Combo Boxes • For a large set of choices, use a combo box • Uses less space than radio buttons • "Combo": combination of a list and a text field • The text field displays the name of the current selection COIT11134 - Java Programming 23 Combo Boxes • If combo box is editable, user can type own selection • Use setEditable method • Add strings with addItem method: JComboBox facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); . . . • Get user selection with getSelectedItem (return type is Object) String selectedString = (String) facenameCombo.getSelectedItem(); • Select an item with setSelectedItem COIT11134 - Java Programming 24 Radio Buttons, Check Boxes, and Combo Boxes • They generate an ActionEvent whenever the user selects an item • An example: ChoiceFrame COIT11134 - Java Programming Continued 25 Radio Buttons, Check Boxes, and Combo Boxes (cont.) • All components notify the same listener object • When user clicks on any component, we ask each component for its current content • Then redraw text sample with the new font COIT11134 - Java Programming 26 Classes of the Font Choice Program COIT11134 - Java Programming 27 ch18/choice/FontViewer.java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: import javax.swing.JFrame; /** This program allows the user to view font effects. */ public class FontViewer { public static void main(String[] args) { JFrame frame = new FontViewerFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("FontViewer"); frame.setVisible(true); } } COIT11134 - Java Programming 28 ch18/ choice/FontViewerFrame.java 001: 002: 003: 004: 005: 006: 007: 008: 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: 020: import import import import import import import import import import import import import import import java.awt.BorderLayout; java.awt.Font; java.awt.GridLayout; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.ButtonGroup; javax.swing.JButton; javax.swing.JCheckBox; javax.swing.JComboBox; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JRadioButton; javax.swing.border.EtchedBorder; javax.swing.border.TitledBorder; /** This frame contains a text field and a control panel to change the font of the text. */ COIT11134 - Java Programming Continued 29 ch18/ choice/FontViewerFrame.java (cont.) 021: public class FontViewerFrame extends JFrame 022: { 023: /** 024: Constructs the frame. 025: */ 026: public FontViewerFrame() 027: { 028: // Construct text sample 029: sampleField = new JLabel("Big Java"); 030: add(sampleField, BorderLayout.CENTER); 031: 032: // This listener is shared among all components 033: class ChoiceListener implements ActionListener 034: { 035: public void actionPerformed(ActionEvent event) 036: { 037: setSampleFont(); 038: } 039: } 040: COIT11134 - Java Programming Continued 30 ch18/ choice/FontViewerFrame.java (cont.) 041: 042: 043: 044: 045: 046: 047: 048: 049: 050: 051: 052: 053: 054: 055: 056: 057: 058: 059: 060: 061: listener = new ChoiceListener(); createControlPanel(); setSampleFont(); setSize(FRAME_WIDTH, FRAME_HEIGHT); } /** Creates the control panel to change the font. */ public void createControlPanel() { JPanel facenamePanel = createComboBox(); JPanel sizeGroupPanel = createCheckBoxes(); JPanel styleGroupPanel = createRadioButtons(); // Line up component panels JPanel controlPanel = new JPanel(); controlPanel.setLayout(new GridLayout(3, 1)); controlPanel.add(facenamePanel); COIT11134 - Java Programming Continued 31 ch18/ choice/FontViewerFrame.java (cont.) 062: 063: 064: 065: 066: 067: 068: 069: 070: 071: 072: 073: 074: 075: 076: 077: 078: 079: 080: 081: 082: controlPanel.add(sizeGroupPanel); controlPanel.add(styleGroupPanel); // Add panels to content pane add(controlPanel, BorderLayout.SOUTH); } /** Creates the combo box with the font style choices. @return the panel containing the combo box */ public JPanel createComboBox() { facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); facenameCombo.addItem("Monospaced"); facenameCombo.setEditable(true); facenameCombo.addActionListener(listener); COIT11134 - Java Programming Continued 32 ch18/ choice/FontViewerFrame.java (cont.) 083: 084: 085: 086: 087: 088: 089: 090: 091: 092: 093: 094: 095: 096: 097: 098: 099: 100: 101: 102: 103: 104: JPanel panel = new JPanel(); panel.add(facenameCombo); return panel; } /** Creates the check boxes for selecting bold and italic styles. @return the panel containing the check boxes */ public JPanel createCheckBoxes() { italicCheckBox = new JCheckBox("Italic"); italicCheckBox.addActionListener(listener); boldCheckBox = new JCheckBox("Bold"); boldCheckBox.addActionListener(listener); JPanel panel = new JPanel(); panel.add(italicCheckBox); panel.add(boldCheckBox); panel.setBorder (new TitledBorder(new EtchedBorder(), "Style")); COIT11134 - Java Programming 33 Continued ch18/ choice/FontViewerFrame.java (cont.) 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: return panel; } /** Creates the radio buttons to select the font size @return the panel containing the radio buttons */ public JPanel createRadioButtons() { smallButton = new JRadioButton("Small"); smallButton.addActionListener(listener); mediumButton = new JRadioButton("Medium"); mediumButton.addActionListener(listener); largeButton = new JRadioButton("Large"); largeButton.addActionListener(listener); largeButton.setSelected(true); // Add radio buttons to button group COIT11134 - Java Programming Continued 34 ch18/ choice/FontViewerFrame.java (cont.) 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton); JPanel panel = new JPanel(); panel.add(smallButton); panel.add(mediumButton); panel.add(largeButton); panel.setBorder (new TitledBorder(new EtchedBorder(), "Size")); return panel; } /** Gets user choice for font name, style, and size and sets the font of the text sample. */ public void setSampleFont() { COIT11134 - Java Programming Continued 35 ch18/ choice/FontViewerFrame.java (cont.) 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: // Get font name String facename = (String) facenameCombo.getSelectedItem(); // Get font style int style = 0; if (italicCheckBox.isSelected()) style = style + Font.ITALIC; if (boldCheckBox.isSelected()) style = style + Font.BOLD; // Get font size int size = 0; final int SMALL_SIZE = 24; final int MEDIUM_SIZE = 36; final int LARGE_SIZE = 48; COIT11134 - Java Programming Continued 36 ch18/ choice/FontViewerFrame.java (cont.) 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: if (smallButton.isSelected()) size = SMALL_SIZE; else if (mediumButton.isSelected()) size = MEDIUM_SIZE; else if (largeButton.isSelected()) size = LARGE_SIZE; // Set font of text field sampleField.setFont(new Font(facename, style, size)); sampleField.repaint(); } private private private private private private private private JLabel sampleField; JCheckBox italicCheckBox; JCheckBox boldCheckBox; JRadioButton smallButton; JRadioButton mediumButton; JRadioButton largeButton; JComboBox facenameCombo; ActionListener listener; COIT11134 - Java Programming Continued 37 ch18/ choice/FontViewerFrame.java (cont.) 190: 191: 192: } private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 400; COIT11134 - Java Programming 38 Self Check 18.3 What is the advantage of a JComboBox over a set of radio buttons? What is the disadvantage? Answer: If you have many options, a set of radio buttons takes up a large area. A combo box can show many options without using up much space. But the user cannot see the options as easily. COIT11134 - Java Programming 39 Self Check 18.4 Why do all user interface components in the FontViewerFrame class share the same listener? Answer: When any of the component settings is changed, the program simply queries all of them and updates the label. COIT11134 - Java Programming 40 Self Check 18.5 Why was the combo box placed inside a panel? What would have happened if it had been added directly to the control panel? Answer: To keep it from growing too large. It would have grown to the same width and height as the two panels below it. COIT11134 - Java Programming 41 How To 18.1 Laying Out a User Interface Step 1: Make a sketch of your desired component layout COIT11134 - Java Programming Continued42 How To 18.1 Laying Out a User Interface (cont.) Step 2: Find groupings of adjacent components with the same layout COIT11134 - Java Programming Continued43 How To 18.1 Laying Out a User Interface (cont.) Step 3: Identify layouts for each group Step 4: Group the groups together Step 5: Write the code to generate the layout COIT11134 - Java Programming 44 GUI Builder COIT11134 - Java Programming 45 Menus • A frame contains a menu bar • The menu bar contains menus • A menu contains submenus and menu items COIT11134 - Java Programming 46 Menu Items • Add menu items and submenus with the add method: JMenuItem fileExitItem = new JMenuItem("Exit"); fileMenu.add(fileExitItem); • A menu item has no further submenus • Menu items generate action events • Add a listener to each menu item: fileExitItem.addActionListener(listener); • Add action listeners only to menu items, not to menus or the menu bar COIT11134 - Java Programming 47 A Sample Program • Builds up a small but typical menu • Traps action events from menu items • To keep program readable, use a separate method for each menu or set of related menus • createFileMenu() • createFileExitItem() • createFontMenu() • createFaceMenu() • createFaceItem() • createSizeMenu() • createSizeItem() • createStyleMenu() • createStyleItem() COIT11134 - Java Programming 48 ch18/menu/FontViewer2.java 01: import javax.swing.JFrame; 02: 03: /** 04: This program allows the user to view font effects. 05: */ 06: public class FontViewer2 07: { 08: public static void main(String[] args) 09: { 10: JFrame frame = new FontViewer2Frame(); 11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12 frame.setVisible(true); 13: } 14:} COIT11134 - Java Programming 49 ch18/menu/FontViewer2Frame.java 001: 002: 003: 004: 005: 006: 007: 008: 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: 020: import java.awt.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class FontViewer2Fram extends Jframe { public FontView2Frame() { sampleField = new Jlabel(“Big Java”); add(sampleField, BorderLayout.CENTER); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); menuBar.add(createFileMenu()); menuBar.add(createFontMenu()); facename = “Serif”; fontsize = 24; fontstyle = Font.PLAIN; setSampleFont(); setSize(FRAME_WIDTH, FRAME_HEIGHT); } COIT11134 - Java Programming Continued 50 ch18/menu/FontViewer2Frame.java (cont.) 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: 036: 037: 038: 039: 040: public JMenu creatFileMenu() { JMenu menu = new JMenu(“File”); menu.add(createFileExitItem()); return menu; } public JMenuItem createFileExitItem() { JMenuItme item = new JMenuItem(“Exit”); class MenuItemListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.exit(0); } } ActionListener listener = new MenuItemListener(); item.addActionListener(listener); return item; } COIT11134 - Java Programming Continued 51 ch18/menu/FontViewer2Frame.java (cont.) 041: 042: 043: 044: 045: 046: 047: 048: 049: 050: 051: 052: 053: 054: 055: 056: 057: 058: 059: 060: 061: public JMenu creatFontMenu() { JMenu menu = new JMenu(“Font”); menu.add(createFaceMenu()); menu.add(createSizeMenu()); menu.add(createStyleMenu()); return menu; } public void createFaceMenu() { …. See textbook page 805 } public void createFaceMenu() { …. See textbook page 806 } … other methods, refer to page 806, 807 Continued ch18/menu/FontViewer2Frame.java (cont.) 145: 146: 147: 148: 149: 150: 151: */ public void setSampleFont() { Font f = new Font(facename, fontstyle, fontsize); sampleField.setFont(f); sampleField.repaint(); } 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: } private private private private private private private private private private JLabel sampleField; JCheckBox italicCheckBox; JCheckBox boldCheckBox; JRadioButton smallButton; JRadioButton mediumButton; JRadioButton largeButton; JComboBox facenameCombo; ActionListener listener; static final int FRAME_WIDTH = 300; static final int FRAME_HEIGHT = 400; Continued Self Check 18.6 Why do JMenu objects not generate action events? Answer: When you open a menu, you have not yet made a selection. Only JMenuItem objects correspond to selections. COIT11134 - Java Programming 54 A Visual Guide to Swing Component (Java Look and Feel) http://java.sun.com/docs/books/tutorial/ui/features/co mponents.html COIT11134 - Java Programming 55 Exploring the Swing Documentation • For more sophisticated effects, explore the Swing documentation • The documentation can be quite intimidating at first glance • Next example will show how to use the documentation to your advantage COIT11134 - Java Programming 56 Example: A Color Viewer • It should be fun to mix your own colors, with a slider for the red, green, and blue values COIT11134 - Java Programming 57 Example: A Color Viewer • How do you know if there is a slider? • Buy a book that illustrates all Swing components • Run sample application included in the JDK that shows off all Swing components • Look at the names of all of the classes that start with J • JSlider seems like a good candidate • Next, ask a few questions: • How do I construct a JSlider? • How can I get notified when the user has moved it? • How can I tell to which value the user has set it? • After mastering sliders, you can find out how to set tick marks, etc. COIT11134 - Java Programming 58 The Swing Demo Set COIT11134 - Java Programming 59 Example: A Color Viewer • There are over 50 methods in JSlider class and over 250 inherited methods • Some method descriptions look scary COIT11134 - Java Programming 60 Continued GUI development summary Program structure (tips) main can be in any class, but it's often simplest to understand if it's in a separate class. main should do very little work -- typically this means just create a window (JFrame) and display it. Events and communication (tips) After the GUI is constructed, the program stops execution until the user does something that causes listener to called. Instance variables are the way a listener typically communications changes. Listener methods (eg, actionPerformed) may be mixed in with the GUI construction code. This makes the code hard to understand. Define methods that these listeners call and put those methods in one place, so the GUI construction can be separated from the GUI execution. COIT11134 - Java Programming 61 GUI development summary(cont.) Events come from Users Controls When you define a user interface, you will usually have some way to get user input. For example, buttons, menus, sliders, mouse clicks, ... all generate events when the user does something with them. User interface event objects are passed from an event source, to an event listener, a user method which will process them. COIT11134 - Java Programming 62 GUI development summary(cont.) Where to declare components? Field variables: This is the appropriate place to declare components which must be referenced after the interface is constructed. Typically these are text fields or text areas, check boxes, etc. Those components whose values must be gotten or set. COIT11134 - Java Programming 63 GUI development summary(cont.) Where to declare components? Local variables should be used for components which are never referenced after the interface is constructed. Typically these are panels for holding components, buttons (whose interaction is thru their listeners), ... Local variables disappear when the method they are in returns, but the component will continue to exist if it has been added to the interface. COIT11134 - Java Programming 64 GUI development summary(cont.) Where to declare components? Anonymous creation is typical with labels, which can be created and added in one step and never assigned to a variable. Of course, if the appearance (font, alignment, ...) must be changed, then they should be put in a local variable. Example content.add(new JLabel("Look at this")); COIT11134 - Java Programming 65 Assignment 1 To develop a GUI application Cover topics: classes, objects, GUI development, Event Handling, Interface, inheritance etc. Use javax.swing components Use java.awt.event for event handling COIT11134 - Java Programming 66 Assignment 1 In this course, you are encouraged to use inner classes for event listeners When generate a component, create listener and add to the component You may group some event sources together to share the same listener if possible COIT11134 - Java Programming 67 Assignment 1 For larger application with more actions, this is a good approach for debugging and maintenance Many development environments automatically generate code with inner classes It is a good idea to be familiar with them COIT11134 - Java Programming 68 Assignment 1 It is OK but not recommend to use a container as a listener (like you did in COIT11222), e.g class MyProject extends JFrame implements ActionListener In above approach, you do not need listener classes, you only need to implement an actionPerformed method in your program COIT11134 - Java Programming 69 Assignment 1 You will need to add actionListener like this button.addActionListner (this); // this means the listener included in this class This approach is OK for small applications COIT11134 - Java Programming 70 Assignment 1 For larger applications, If you have many components with many different actions, you need to use lots of if-then-else to decide what event resource and what action to take in actionPerformed method Makes debugging and maintenance very difficult Play with the executable assignment 1 from the course website. COIT11134 - Java Programming 71 References Horstmann C. “Big Java”. COIT11134 - Java Programming 72