Chapter 12

Chapter 12

Chapter 13: GUI ApplicationsPart 2 Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260 Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Topics Chapter 13 discusses the following main topics: o Read-Only Text Fields o Lists o Combo Boxes o Displaying Images in Labels and Buttons

o Mnemonics and Tool Tips o Color Chooser Dialog o Menus o More about Text Components: Text Areas and Fonts o Sliders o Look and Feel Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-2 TextFields for output only READ-ONLY TEXT FIELDS Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-3 Read Only Text Fields A JTextField may be made output-only, not allowing the user to type into it The JTextField component has a method named setEditable: setEditable (boolean editable) By default a text field is editable The setEditable method must be called and passed false to make the field read-only Editable and Read-Only TextFields

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-4 Controls for displaying Lists in a GUI application JLIST Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-5 Lists A list is a component that displays a list of items and allows the user to select items from the list

The JList generic component is used for creating lists of objects of the specified type When an instance of JList is created, an array of the proper type is passed to the constructor JList (String[ ] array) The JList uses the array to create the list of items String[] names = { "Bill", "Geri", "Greg", "Jean", "Kirk", "Phillip", "Susan" }; JList nameList; nameList = new JList(names); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-6

List Selection Modes The generic JList component can operate in any of the following selection modes: o Single Selection Mode - Only one item can be selected at a time o Single Interval Selection Mode - Multiple items can be selected, but they must be in a single contiguous interval. An interval is a set of contiguous items such as items 3, 4, and 5 o Multiple Interval Selection Mode - In this mode multiple items may be selected with no restrictions This is the default selection mode Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-7 List Selection Modes Single selection mode allows only one item to be selected at a time. Multiple interval selection mode allows multiple items to be selected with no restrictions. Single interval selection mode allows a single interval of contiguous items to be selected.

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-8 List Selection Modes You change a JList components selection mode with the setSelectionMode method The method accepts an int argument that determines the selection mode: o ListSelectionModel.SINGLE_SELECTION o ListSelectionModel.SINGLE_INTERVAL_SELECTION o ListSelectionModel.MULTIPLE_INTERVAL_SELECTION

Example: nameList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-9 List Events When an item in a JList object is selected it generates a list selection event The event is handled by an instance of a list selection listener class, which must meet the following requirements: o It must implement the ListSelectionListener interface

o It must have a method named valueChanged. This method must take an argument of the ListSelectionEvent type Use the addListSelectionListener method of the JList class to register the instance of the list selection listener class with the list object Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-10 List Events When the JList component generates an event: o it automatically executes the valueChanged method of the list selection

listener object o It passes the event object as an argument Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-11 Retrieving Selected Items You may use: getSelectedValue or getSelectedIndex to determine which item in a list is currently selected getSelectedValue returns a reference to the item

that is currently selected String selectedName; selectedName = nameList.getSelectedValue( ); If no item in the list is selected, the method returns null Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-12 Retrieving Selected Items The getSelectedIndex method returns the index of the selected item or 1 if no item is selected Internally, the items that are stored in a list are numbered

(similar to an array) Each items number is called its index The first item has the index 0 You can use the index of the selected item to retrieve the item from the associated array String[] names = { "Bill", "Geri", "Greg", "Jean", "Kirk", "Phillip", "Susan" }; JList nameList = new JList(names); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-13 Retrieving Selected Items

This code could be used to determine the selected item: int index; String selectedName; index = nameList.getSelectedIndex( ); if (index != -1) selectedName = names[index]; Example: ListWindow.java Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Here, names is the array of Strings from

which the nameList was populated 12-14 Bordered Lists The setBorder method can be used to draw a border around a JList monthList.setBorder( BorderFactory.createLineBorder(Color.black,1)); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-15

Adding A Scroll Bar To a List By default, a list component is expected to be large enough to display all of the items it contains Sometimes, a list component contains too many items to be displayed at once Most GUI applications provide a scroll bar on list components that contain a large number of items List components do not automatically display a scroll bar Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-16 Adding A Scroll Bar To a List

To display a scroll bar on a list component, follow these general steps 1. Set the number of visible rows for the list component 2. Create a JScrollPane object and add the list component to it 3. Add the JScrollPane object to another container, such as a panel or the content pane For this list String[] names = { "Bill", "Geri", "Greg", "Jean", "Kirk", "Phillip", "Susan" }; JList nameList = new JList(names); see the next slide for the conclusion of this example Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-17 Adding A Scroll Bar To a List Establish the size of the list component. For example: nameList.setVisibleRowCount(3); Create a scroll pane object and add the list component to it A scroll pane object is a container that displays a scroll bar on any component it contains The JScrollPane class to create a scroll pane object We pass the object that we wish to add to the scroll pane as an argument to the JScrollPane constructor JScrollPane scrollPane = new

JScrollPane (nameList); Continued Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-18 Adding A Scroll Bar To a List Add the scroll pane object to any other containers that are necessary for our GUI JPanel panel = new JPanel( ); panel.add (scrollPane); add (panel); When the list component is displayed, it will

appear with: o Three items showing at a time o Scroll bars Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-19 Adding A Scroll Bar To a List By default, JList components added to a JScrollPane object only display a scroll bar if there are more items in the list than there are visible rows When a JList component is added to a JScrollPane object, a border will appear around the list

Array of Strings containing the month names Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-20 Setting Fixed List Width One may wish, on occasion, to set the width of the list to a fixed size The default width is the width needed to display the contents of the list (an empty list has 0 width) For example, if you plan to show an empty list initially, you may want to set its width

This can be done with the JList method setFixedCellWidth (int) // parameter is in pixels For example: nameList.setFixedCellWidth (275); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-21 Adding Items to an Existing List The setListData method allows modification of items in an existing JList component void setListData (String[ ] data) The new data replaces any items that are currently displayed in the component

This can be used to add or delete items in a list by replacing the old list with a new list containing only the desired items While the argument to setListData must be an array, one may use the ArrayLists toArray method to convert an ArrayList to an array as in nameList.setListData(nameArrayList.toArray ( )); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-22 Adding Items to an Existing List You can create an empty list by using the JList components no-parameter constructor: JList nameList = new

JList(); Items can be added to the list: String[] names = { "Bill", "Geri", "Greg", "Jean", "Kirk", "Phillip", "Susan" }; nameList.setListData (names); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-23 Single Interval Selection Mode A list is set to single interval selection mode by passing the constant ListSelectionModel.SINGLE_INTERVAL_SELECTION

to the components setSelectionMode method An interval is a set of contiguous items The user selects: o the first item in the interval by clicking on it olast item by holding the Shift key while clicking on it All of the items that appear in the list from the first item through the last item are selected Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-24 Single Interval Selection Mode

The getSelectedValue method returns the first item in the selected interval The getSelectedIndex method returns the index of the first item in the selected interval To get the entire selected interval, use the getSelectedValues method o This method returns an array of objects, which are the items in the selected interval The getSelectedIndices method returns an array of int values that are the indices of all the selected items in the list Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-25 Multiple Interval Selection Mode Set multiple interval selection mode by passing the constant ListSelectionModel.MULTIPLE_INTERVAL_SELECTION to the components setSelectionMode method In multiple interval selection mode: o multiple items can be selected o the items do not have to be in the same interval In multiple interval selection mode the user can select single items or intervals

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-26 Multiple Interval Selection Mode The user holds down the Ctrl key while clicking on an item o it selects the item without deselecting other items The getSelectedValue method returns the first selected item The getSelectedIndex method returns the index of the first selected item The getSelectedValues method returns an array of objects containing all the items that are selected The getSelectedIndices method returns an int array containing the indices of all the selected items

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-27 Multiple Interval Selection Mode Example: MultipleIntervalSelection.java Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-28 Generic drop-down ComboBox combines List with TextField control

JCOMBOBOX Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-29 Combo Boxes A combo box presents a drop-down list of items that the user may select from The JComboBox class is used to create a combo box Pass an array of objects that are to be displayed as the items in the drop-down list to the constructor String[] names = { "Bill", "Geri", "Greg", "Jean",

"Kirk", "Phillip", "Susan" }; JComboBox nameBox = new JComboBox (names); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-30 Combo Boxes The button displays the item that is currently selected The first item in the list is automatically selected when the combo box is displayed When the user clicks on the button,

the drop-down list appears and the user may select a different item Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-31 Combo Box Events When an item in a JComboBox object is selected, it generates an action event Handle action events with an action event listener class, which must have an actionPerformed method When the user selects an item in a combo box, the JVM executes the action event listeners

actionPerformed method, passing an ActionEvent object as an argument Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-32 Retrieving Selected Items Similar to the JList, there are two methods in the JComboBox class that can be used to determine which item in a list is currently selected: o getSelectedItem o getSelectedIndex The getSelectedItem method returns a reference

to the item that is currently selected String selectedName; selectedName = nameBox.getSelectedItem( ); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-33 Retrieving Selected Items The getSelectedIndex method returns the index of the selected item String[] names = { "Bill", "Geri", "Greg", "Jean", "Kirk", "Phillip", "Susan" }; JComboBox nameBox = new JComboBox(names);

Get the selected item from the names array: int index; String selectedName; index = nameBox.getSelectedIndex( ); selectedName = names[index]; Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-34 Retrieving Selected Items Example: ComboBoxWindow.java

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-35 Editable Combo Boxes There are two types of combo boxes: o uneditable allows the user to only select items from its list o editable combines a text field and a list It allows the selection of items from the list Allows the user to type input into the text field The setEditable method sets the edit mode for the component String[] names = { "Bill", "Geri", "Greg",

"Jean", "Kirk", "Phillip", "Susan" }; JComboBox nameBox = new JComboBox (names); nameBox.setEditable (true); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-36 Editable Combo Boxes An editable combo box appears as a text field with a small button displaying an arrow joining it When the user clicks on the button, the dropdown list appears as shown in the center of the figure

The user may: o Select an item from the list o Type a value into the text field The user is not restricted to typing the values that already appear in the list, and may type any input into the text field Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-37 Editable Combo Boxes Note that Sharon is not in the list. Original

appearance of editable dropdown ComboBox Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sharon has been typed over Bill Dropped down editable ComboBox

12-38 Displaying Graphics PICTURES AND ICONS Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-39 Displaying Images in Labels and Buttons Labels can display text, an image, or both To display an image, create an instance of the ImageIcon class, which reads the image file

The constructor accepts name of an image file The supported file types are JPEG, GIF, and PNG Name may contain path information ImageIcon image = new ImageIcon("Smiley.gif"); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Relative path; Pictures is folder in project 12-40 Displaying Images in Labels and Buttons Display the image in a label by passing the

ImageIcon object as an argument to the JLabel constructor JLabel (Icon image) The argument passed can be an ImageIcon object or any object that implements the Icon interface ImageIcon image = new ImageIcon("Smiley.gif"); JLabel label = new JLabel(image); or Has image JLabel label = new JLabel("Have a nice day!"); label.setIcon (image); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Has both image and text only 12-41 Displaying Images in Labels and Buttons Text is displayed to the right of images by default Text alignment can be modified by passing one of the following to an overloaded constructor: o SwingConstants.LEFT o SwingConstants.CENTER o SwingConstants.RIGHT

Example: ImageIcon image = new ImageIcon("Smiley.gif"); JLabel label = new JLabel("Have a nice day!", image, SwingConstants.RIGHT); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-42 Displaying Images in Labels and Buttons Creating a button with an image is similar to that of creating a label with an image

ImageIcon image = new ImageIcon("Smiley.gif"); JButton button = new JButton (image); To create a button with an image and text: ImageIcon image = new ImageIcon("Smiley.gif"); JButton button = new JButton( "Have a nice day!", image); button.setIcon (image);

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-43 Displaying Images in Labels and Buttons To add an image to an existing button: JButton button = new JButton(Get Image"); ImageIcon image = new ImageIcon("Smiley.gif"); button.setIcon (image); Picture replaced label text Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-44 Setting a JFrame Icon Relative path does not include the drive letter just the path relative to the project folder Picture files are often stored in a separate folder in the project. Here the Pictures folder holds multiple .jpg and .png files. The .java files are in the src folder. 12-45

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Resource for Icons http://www.axialis.com/icongenerator/ Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-46 IconGenerator, continued Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-47

Mnemonics A mnemonic is a key that you press in combination with the Alt key to access a component quickly These are sometimes referred to as hot keys A hot key is assigned to a component through the components setMnemonic method The argument passed to the method is an integer code that represents the key you wish to assign Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-48

Mnemonics The key codes are predefined constants in the KeyEvent class (java.awt.event package) These constants take the form: o KeyEvent.VK_x, where x is a key on the keyboard The letters VK in the constants stand for virtual key o To assign the A key as a mnemonic, use KeyEvent.VK_A Example: JButton exitButton = new JButton("Exit"); exitButton.setMnemonic (KeyEvent.VK_X); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-49

Mnemonics If the letter is in the components text, the first occurrence of that letter will appear underlined If the letter does not appear in the components text, then no letter will appear underlined One may have to press the ALT key to see the underlines in some operating systems Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-50 Mnemonics You can also assign mnemonics to radio buttons

and check boxes: JRadioButton rb1 = new JRadioButton("Breakfast"); rb1.setMnemonic (KeyEvent.VK_B); JRadioButton rb2 = new JRadioButton ("Lunch"); rb2.setMnemonic (KeyEvent.VK_L); JCheckBox cb1 = cb1.setMnemonic JCheckBox cb2 = cb2.setMnemonic new JCheckBox ("Monday"); (KeyEvent.VK_M); new JCheckBox ("Wednesday"); (KeyEvent.VK_W);

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-51 Tool Tips A tool tip is text that is displayed in a small box when the mouse is held over a component The box usually gives a short description of what the component does Most GUI applications use tool tips as concise help to the user Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-52

Tool Tips Assign a tool tip to a component with the setToolTipText method JButton submit = new JButton(Submit"); submit.setMnemonic (KeyEvent.VK_M); submit.setToolTipText( Place the order and reset the window"); Note the mnemonic m Tool tip Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-53

Tool-tip Example Tool tip for JList is displayed when cursor hovers over it Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-54 Select a color using a Java Dialog box COLOR CHOOSER DIALOG

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-55 Color Choosers A color chooser is a specialized dialog box that allows the user to select a color from a predefined palette of colors Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-56 Color Choosers By clicking the HSB tab you can select a color by

specifying its hue, saturation, and brightness By clicking the RGB tab you can select a color by specifying its red, green, and blue components The JColorChooser class has a static method named showDialog, with the following general calling sequence: Color showDialog (Component parent, String title, Color initial) Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-57 Color Choosers

If the first argument is null, the dialog box is normally centered in the screen If it is a reference to a component the dialog box is displayed over the component The second argument is the dialog caption The third argument indicates the color that appears as initially selected in the dialog box This method returns the color selected by the user Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-58 Color Choosers

Example: JPanel panel = new JPanel( ); Color selectedColor = JColorChooser.showDialog (null, "Select a Background Color", Color.BLUE); panel.setBackground (selectedColor); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-59 GUI MENUS IN JAVA Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-60 Menus A menu system is a collection of commands organized in one or more drop-down menus Menubar Menu Separator Check Box Menu Item Menu Items }

Submenu Radio Button Menu Item Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-61 Components of A Menu System A menu system commonly consists of: o Menu Bar A menu bar lists the names of one or more menus o Menu A menu is a drop-down list of menu items o Menu Item A menu item can be selected by the user

o Check box menu item A check box menu item appears with a small box beside it The item may be selected or deselected o Radio button menu item A radio button menu item may be selected or deselected o Submenu A menu within a menu is called a submenu o Separator bar A separator bar is a horizontal bar used to separate groups of items on a menu Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-62 Menu Classes

A menu system is constructed with the following classes: o JMenuBar Used to create a menu bar A JMenuBar object can contain JMenu components o JMenu Used to create a menu. A JMenu component can contain 0 or more of these: JMenuItem, JCheckBoxMenuItem, and JRadioButtonMenuItem components,

as well as other JMenu components. A submenu is a JMenu component that is inside another JMenu component o JMenuItem Used to create a regular menu item A JMenuItem component generates an action event when selected Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-63 Menu Classes o JCheckBoxMenuItem Used to create a check box menu item The classs isSelected method returns true if the item is selected, or false otherwise A JCheckBoxMenuItem component generates an action event when selected o JRadioButtonMenuItem Used to create a radio button menu item JRadioButtonMenuItem components can be grouped together in a ButtonGroup object so that only one of them can be selected at a time The classs isSelected method returns true if the item is selected, or false otherwise A JRadioButtonMenuItem component generates an action event when

selected To attach a JMenuBar to a JFrame window, use something like the following with the JFrame class: this.setJMenuBar (myMenuBar); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-64 Menu Example JMenuBar with 3 JMenus 3 JMenuItems Add items to Menu,

Menus to MenuBar Create menu items and register listeners 12-65 Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Menu Example Menu Example: MenuWindow.java Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-66 Adding Icons to menu items Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-67 Multiline text fields TEXT AREAS Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-68 Text Areas The JTextField class is used to create text fields A text field is a component that allows the user to enter a single line of text

A text area is like a text field but it can accept multiple lines of input You use the JTextArea class to create a text area The general format of two of the classs constructors: JTextArea (int rows, int columns) JTextArea (String text, int rows, int columns) Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-69 Text Areas The JTextArea class provides the getText and setText methods for getting and setting the text String userText = textInput.getText ( );

textInput.setText ("Modified: " + userText); JTextArea components do not automatically display scroll bars If you want to scroll, you must add the text area to a scroll pane JTextArea textInput = JTextArea (20, 40); JScrollPane scrollPane = new JScrollPane (textInput); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-70 Text Areas The JScrollPane object displays both vertical

and horizontal scroll bars on a text area By default, the scroll bars are not displayed until they are needed This behavior can be altered: scrollPane.setHorizontalScrollBarPolicy ( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setVerticalScrollBarPolicy ( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-71 Text Areas You can pass one of the following constants as an

argument: o setHorizontalScrollBarPolicy JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED JScrollPane.HORIZONTAL_SCROLLBAR_NEVER JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS o setVericalScrollBarPolicy JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED JScrollPane.VERTICAL_SCROLLBAR_NEVER JScrollPane.VERTICAL_SCROLLBAR_ALWAYS Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-72

Text Areas By default, JTextArea components do not perform line wrapping To enable line wrapping: textInput.setLineWrap (true); There are two different styles of line wrapping: o word wrapping all line breaks occur between words textInput.setWrapStyleWord (true); o character wrapping lines are broken between characters (default mode) Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-73

Text Area Example Entire content pane area is occupied by one large JTextArea controls Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-74 Fonts in Java GUI applications WORKING WITH FONTS

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-75 Fonts Components display according to their font characteristics: o font the name of the typeface o style can be plain, bold, and/or italic o size size of the text in points A components setFont method will change the appearance of the text in the component: setFont (Font appearance)

A Font constructor takes three parameters: Font(String fontName, int style, int size) Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-76 Fonts Java guarantees that you will have the fonts: o Dialog, DialogInput, Monospaced, SansSerif, and Serif There are three font styles: o Font.PLAIN, Font.BOLD, and Font.ITALIC Example:

label.setFont (new Font("Serif", Font.BOLD, 24)); Font styles can be combined adding them label.setFont (new Font("Serif", Font.BOLD + Font.ITALIC, 24)); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-77 Font Examples Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-78

Selecting a value from a range of values THE SLIDER CONTROL Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-79 Sliders A slider is a component that allows the user to graphically adjust a number within a range Sliders are created from the

JSlider class They display an image of a slider knob (also called a thumb) that can be dragged along a track Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-80 Sliders A slider is designed to represent a range of numeric values As the user moves the knob along the track, the numeric value is adjusted accordingly

Between the minimum and maximum values, major tick marks are displayed Each major tick mark has a label indicating the value at that tick mark Between the major tick marks are minor tick marks Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-81 Sliders The JSlider constructor has the general format: JSlider(int orientation, int minValue, int maxValue, int initialValue)

For orientation, one of these constants should be used: o JSlider.HORIZONTAL o JSlider.VERTICAL Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-82 Sliders Example: JSlider slider1 = new JSlider (JSlider.HORIZONTAL, 0, 50, 25); JSlider slider2 = new JSlider (JSlider.VERTICAL, 0, 50, 25);

Set the major and minor tick mark spacing with: o setMajorTickSpacing o setMinorTickSpacing Example: slider1.setMajorTickSpacing(10); slider1.setMinorTickSpacing(2); Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-83 Sliders Display tick marks by calling: o setPaintTickMarks

slider1.setPaintTickMarks(true); Display numeric labels on the slider by calling: o setPaintLabels slider1.setPaintLabels(true); When the knobs position is moved, the slider component generates a change event To handle the change event, write a change listener class Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-84 Sliders A change listener class must meet the requirements:

o It must implement the ChangeListener interface o It must have a method named stateChanged This method must take an argument of the ChangeEvent type To retrieve the current value stored in a JSlider, use the getValue method currentValue = slider1.getValue ( ); Example: TempConverter.java Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-85 Setting the look-and-feel of a GUI application JAVA LOOK-AND-FEEL Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-86 Look and Feel The appearance of a particular systems GUI is known as its look and feel Java allows you to select the look and feel of a GUI application

On most systems, Javas default look and feel is called Metal There are also Motif and Windows look and feel classes for Java o Motif is similar to a UNIX look and feel o Windows is the look and feel of the Windows operating system Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-87 Look and Feel To change an applications look and feel, call the UIManager classs static setLookAndFeel method

Java has a class for each look and feel The setLookAndFeel method takes the fully qualified class name for the desired look and feel as its argument The class name must be passed as a string Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-88 Look and Feel Metal look and feel: "javax.swing.plaf.metal.MetalLookAndFeel" Motif look and feel:

"com.sun.java.swing.plaf.motif.MotifLookAndFeel" Windows look and feel: "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-89 Look and Feel Metal Motif Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Windows 12-90 Look and Feel Any components that have already been created need to be updated SwingUtilities.updateComponentTreeUI(); This method takes a reference to the component that you want to update as an argument The UIManager.setLookAndFeel method throws a number of exceptions: o

o o o ClassNotFoundException InstantiationException IllegalAccessException UnsupportedLookAndFeelException Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-91 Look and Feel Example (Motif):

try { UIManager.setLookAndFeel ( "com.sun.java.swing.plaf.motif.MotifLookAndFeel"); SwingUtilities.updateComponentTreeUI (this); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error setting the look and feel."); System.exit(0); }

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-92 Look and Feel Example (Windows): try { UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); SwingUtilities.updateComponentTreeUI (this);

} catch (Exception e) { JOptionPane.showMessageDialog(null, "Error setting the look and feel."); System.exit(0); } Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-93 Changing Look and Feel Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

12-94 Creating your own secondary windows using JDialog CUSTOM DIALOGS IN JAVA Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-95 Custom Dialogs A number of dialogs are provided by Java and Swing Some that we have experienced include

JOptionPanes ConfirmDialog, MessageDialog, and InputDialog JFileChooser JColorChooser We can also create our own custom dialog by deriving a class from JDialog Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-96 The JDialog Class JDialog and JFrame have many features in common Most of the things one can do with JFrame can also be done with JDialog

A dialog is usually considered a secondary window that accomplishes a subtask of the primary application A dialog is frequently displayed as a result of something that happens in another class such as A menu choice is selected A button is clicked or a list selection made An exception is caught/handled Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-97 JDialog Constructor One of the constructors for JDialog has the form JDialog (Dialog owner, String title, boolean modal)

The owner is the parent window the one that instantiated the instance of the dialog class The title is the dialogs caption The modality is true for a modal dialog and false for a modeless dialog A modal dialog locks the parent until the dialog is dismissed no further processing takes place in the parent while the dialog is displayed A modeless dialog may be visible and allow user interaction side-byside with interaction with the parent window One can find examples in Microsoft Word where the Open dialog is modal while the find/replace dialog is modeless Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-98

Dialog Constructor Example Constructor receives a reference to its parent window; used in lines 58 and 68 Lines 62, 63, and 65 are calls to other methods in this class that do what their names suggest Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-99

Using a Custom Dialog Object From a JFrame-derived class (MainWindow in this case), instantiate an object of the JDialogderived class Instantiate a new object of the class named AboutDialog (see prev. slide), passing a reference to the current instance of the MainWindow class to its constructor as its parent Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-100

Dialog Contents Each dialog is designed for its own purpose It may simply inform the user of something as in an About dialog It may allow 2-way interaction with the user as in a JFileChooser or JColorChooser dialog A dialog may have all of the controls that a JFrame may have such as panels, text fields, labels, lists, buttons, check boxes, and so forth A JDialog is created in essentially the same way as a JFrame is Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-101

Timer Control measures time in milliseconds USING A TIMER CONTROL Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-102 Timer Control Timer class constructor takes 2 parameters First is number of milliseconds it will run before it generates a Tick event 1000 milliseconds sets the timer to 1 second 3500 milliseconds sets the time to 3.5 seconds

Instance of its Tick Event Listener class Registers the listener Uses an ActionListener with its actionPerformed method Two other methods start causes the timer to begin timing setRepeats (true) causes the timer to begin timing again as soon as it generates a Tick event Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-103 Digital clock example private attributes

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-104 Timer setup for digital clock example The following creates a timer, sets it to generate a Tick event every one second, and registers a listener named TickListener Start the timer Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Specify that the timer restarts when it expires

13-105 Constructor for Digital Clock example Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-106 Digital Clock Example set and update clock JFrame caption is the date; time label text is

current time Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-107 Digital Clock example continued Update the date and the time whenever the timer ticks (every one second) Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-108 Example of the Digital Clock

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13-109

Recently Viewed Presentations