Chapter 17 GUI Programming Component Layout Additional GUI

  • Slides: 57
Download presentation
Chapter 17 GUI Programming - Component Layout, Additional GUI Components n n n n

Chapter 17 GUI Programming - Component Layout, Additional GUI Components n n n n n Layout Managers Assigning the Layout Manager Flow. Layout Alignment Layout Changes Border. Layout Manager Label Alignment Grid. Layout Manager Tic-Tac-Toe Program Embedded Layout Managers JPanel Class Math. Calculator Program JText. Area Component JCheck. Box Component JRadio. Button Component JCombo. Box Component Job Application Example 1

Layout Managers n n n Layout managers automate the positioning of components within containers.

Layout Managers n n n Layout managers automate the positioning of components within containers. They free the programmer from the difficult task of figuring out the space needed for each component and the pixel coordinate positions for each component. The layout manager looks at the size of its container and the sizes of the container's components. It then tries to fit the components neatly into the container. If a user resizes the window, the layout manager takes that into account and adjusts the layout accordingly. If a programmer adjusts a component's size (e. g. , by changing a label's font size), the layout manager takes that into account and adjusts the layout accordingly. 2

Layout Managers n The four most common layout manager classes: n n n Flow.

Layout Managers n The four most common layout manager classes: n n n Flow. Layout Border. Layout Grid. Bag. Layout All of these layout manager classes are in the java. awt package so import that package. 3

Assigning the Layout Manager n To assign a particular layout manager to a JFrame

Assigning the Layout Manager n To assign a particular layout manager to a JFrame window, call the set. Layout method as follows: set. Layout(new <layout manager class>()); n n In the above code template, replace <layout manager class>by one of the layout manager classes (e. g. , Flow. Layout, Border. Layout, Grid. Layout). If set. Layout is not called, then the Border. Layout manager is used (because that's the default layout manager for a JFrame window). 4

Flow. Layout Manager n n n The Flow. Layout class implements a simple onecompartment

Flow. Layout Manager n n n The Flow. Layout class implements a simple onecompartment layout scheme that allows multiple components to be inserted into the compartment. When a component is added to the compartment, it is placed to the right of any components that were previously added to the compartment. If there is not enough room to add a component to the right of previously added components, then the new component is placed on the next line (i. e. , it "flows" to the next line). 5

Flow. Layout Alignment n n By default, components are placed in a Flow. Layout

Flow. Layout Alignment n n By default, components are placed in a Flow. Layout container using top, center alignment. There's no way to change the vertical alignment. But there is a way to change the horizontal alignment. To do so, insert one of the Flow. Layout alignment constants (Flow. Layout. LEFT, Flow. Layout. CENTER, Flow. Layout. RIGHT) in the Flow. Layout constructor call. For example, here's how to specify left alignment: set. Layout(new Flow. Layout(Flow. Layout. LEFT)); 6

Layout Changes n 7 Normally, set. Layout is called just once - when the

Layout Changes n 7 Normally, set. Layout is called just once - when the program initially lays out its components. But if there's a need to dynamically adjust the layout scheme, call set. Layout again. For example, if you need to move a container's components to the right, reassign the layout like this: set. Layout(new Flow. Layout(Flow. Layout. RIGHT)); validate(); n n The validate method causes the layout manager to regenerate the component layout. If your window is visible (i. e. , you've called set. Visible(true)), and you attempt to change its layout in some way, you'll need to call validate to make the change take effect. These method calls attempt to change the layout: n n n set. Layout - to adjust the layout scheme add - to add a component set. Size - to change the window's size

Border. Layout Manager n n The Border. Layout manager provides five regions/compartments in which

Border. Layout Manager n n The Border. Layout manager provides five regions/compartments in which to insert components. The sizes of the five regions are determined at run time, and they're based on the contents of each region. n n Thus, if the west region contains a long label, the layout manager attempts to widen the west region. Likewise, if the west region contains a short label, the layout manager attempts to narrow the west region. 8

Border. Layout Manager n More specifically, the sizes of the five regions are determined

Border. Layout Manager n More specifically, the sizes of the five regions are determined as shown below. West's contents determines this divider's position. North's contents determines this divider's position. South's contents determines this divider's position. East's contents determines this divider's position. 9

Border. Layout Manager n n If an outer region (North, South, East, West) is

Border. Layout Manager n n If an outer region (North, South, East, West) is empty, it collapses so that it does not take up any space. For example: n n n What happens if the north region is empty? What happens if the east and south regions are both empty? What happens if the center region is empty? 10

Border. Layout Manager n To add a component to a Border. Layout region, call

Border. Layout Manager n To add a component to a Border. Layout region, call the container's add method like this: add(<component>, <region>); n Replace <component> by a component (a JLabel object, a JButton object, etc. ) and replace <region> by one of these named constants: n n n Border. Layout. NORTH, Border. Layout. SOUTH, Border. Layout. WEST, Border. Layout. EAST, Border. Layout. CENTER In the add method call, if the region argument is omitted, then the center region is used (because that's the default region). With a Border. Layout container, you can add only five components total, one for each of the five regions. If you add a component to a region that already has a component, then the new component overlays the old component. 11

African. Countries Program with Buttons import javax. swing. *; import java. awt. *; public

African. Countries Program with Buttons import javax. swing. *; import java. awt. *; public class African. Countries extends JFrame { private static final int WIDTH = 325; private static final int HEIGHT = 200; public African. Countries() { set. Size(WIDTH, HEIGHT); set. Title("African Countries"); set. Default. Close. Operation(EXIT_ON_CLOSE); set. Layout(new Border. Layout()); add(new JButton("Tunisia"), Border. Layout. NORTH); add(new JButton("<html>South Africa</html>"), Border. Layout. SOUTH); add(new JButton("Western Sahara"), Border. Layout. WEST); add(new JButton("Central African Republic"), Border. Layout. CENTER); add(new JButton("Somalia"), Border. Layout. EAST); set. Visible(true); } // end African. Countries constructor //******************* public static void main(String[] args) { new African. Countries(); } // end main } // end class African. Countries 12

Label Alignment n To specify a label's alignment within a Border. Layout region, instantiate

Label Alignment n To specify a label's alignment within a Border. Layout region, instantiate the label with an alignment constant like this: new JLabel(<label's text>, <alignment constant>) n Replace <alignment constant> by one of these named constants: n n Swing. Constants. LEFT, Swing. Constants. CENTER, Swing. Constants. RIGHT Here's an example that adds a center-aligned label to a Border. Layout north region: add(new JLabel("Tunisia", Swing. Constants. CENTER), Border. Layout. NORTH); 14

Label Alignment n n n Swing. Constants is an interface, defined in the javax.

Label Alignment n n n Swing. Constants is an interface, defined in the javax. swing package. Swing. Constants stores a set of GUI-related constants that are commonly used by many different GUI programs. To access a named constant in an interface, prefix it with the interface name. For example, to access the LEFT alignment constant, prefix LEFT with Swing. Constants like this: Swing. Constants. LEFT. 15

Grid. Layout Manager n n The Grid. Layout manager lays out a container's components

Grid. Layout Manager n n The Grid. Layout manager lays out a container's components in a rectangular grid. The grid is divided into equal-sized cells. Each cell can hold only one component. To specify the use of a Grid. Layout manager for a particular container, call set. Layout like this: set. Layout(new Grid. Layout(rows, cols, h. Gap, v. Gap)); # of rows # of columns Gap between columns, in pixels. Default value = 0. Gap between rows, in pixels. Default value = 0. 16

Adding Components n To add a component to one of the container's cells, call

Adding Components n To add a component to one of the container's cells, call the add method like this: add(<component>); n The Grid. Layout manager positions components within the container using left-to-right, top-to-bottom order. The first added component goes in the top-left-corner cell, the next added component goes in the cell to the right of the first component, etc. 17

Grid. Layout Manager n Here's an example that displays a two-row, three-column table with

Grid. Layout Manager n Here's an example that displays a two-row, three-column table with six buttons: set. Layout(new Grid. Layout(2, 3, 5, 5)); add(new JButton("1")); add(new JButton("2")); add(new JButton("3")); add(new JButton("4")); add(new JButton("5")); add(new JButton("6")); 18

19 Specifying Number of Rows and Number of Columns n Case 1: n n

19 Specifying Number of Rows and Number of Columns n Case 1: n n If you know the number of rows and columns in your table and the table is completely filled in (i. e. , there are no empty cells), call the Grid. Layout constructor with the actual number of rows and the actual number of columns. Case 2: n n n Sometimes, you might want a row-oriented display. If that's the case, call the Grid. Layout constructor with the actual number of rows for the rows argument and 0 for the columns argument. A 0 for the columns argument indicates that you're leaving it up to the Grid. Layout manager to determine the number of columns.

20 Specifying Number of Rows and Number of Columns n Case 2 (continued): n

20 Specifying Number of Rows and Number of Columns n Case 2 (continued): n Assume that you assign a container's layout like this: set. Layout(new Grid. Layout(2, 0)); n n Assume that you add 5 components to the container. Here's the resulting display:

21 Specifying Number of Rows and Number of Columns n Case 3: n n

21 Specifying Number of Rows and Number of Columns n Case 3: n n n Sometimes, you might want a column-oriented display. If that's the case, call the Grid. Layout constructor with the actual number of columns for the columns argument and 0 for the rows argument. Assume that you assign a container's layout like this: set. Layout(new Grid. Layout(0, 4)); n After adding 5 components to the container, here's the resulting display:

Common Errors n If you call the Grid. Layout constructor with 0's for both

Common Errors n If you call the Grid. Layout constructor with 0's for both the rows and columns arguments, you'll get a compilation error; i. e. , this generates a compilation error: set. Layout(new Grid. Layout(0, 0)); n n If you call the Grid. Layout constructor with non-0's for both the rows and columns arguments and your table is not completely filled, you may get unexpected results. For example, the previous slide's four-column window is not completely filled. Suppose you accidentally specify a value for the rows argument: set. Layout(new Grid. Layout(2, 4)); n After adding 5 components to the container, here's the resulting display: 22

Tic-Tac-Toe Program import javax. swing. *; import java. awt. event. *; This program displays

Tic-Tac-Toe Program import javax. swing. *; import java. awt. event. *; This program displays a 3 x 3 grid of blank buttons. When the first blank button is clicked, its label changes to an X. Subsequent clicked blank buttons change their labels to O and X in alternating sequence. public class Tic. Tac. Toe extends JFrame { private boolean x. Turn = true; // keeps track of whether // it's X's turn or O's turn //******************** public Tic. Tac. Toe() { set. Size(200, 220); set. Title("Tic-Tac-Toe"); set. Default. Close. Operation(EXIT_ON_CLOSE); create. Contents(); set. Visible(true); } // end Tic. Tac. Toe constructor 23

Tic-Tac-Toe Program //******************* // Create components and add to window. private void create. Contents()

Tic-Tac-Toe Program //******************* // Create components and add to window. private void create. Contents() { JButton button; // re-instantiate this button and use // to fill entire board set. Layout(new Grid. Layout(3, 3)); for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { button = new JButton(); button. add. Action. Listener(new Listener()); add(button); } // end for j } // end for i } // end create. Contents 24

Tic-Tac-Toe Program 25 //******************** // If user clicks a button, change its label to

Tic-Tac-Toe Program 25 //******************** // If user clicks a button, change its label to "X" or "O". private class Listener implements Action. Listener { public void action. Performed(Action. Event e) { JButton btn = (JButton) e. get. Source(); if (btn. get. Text(). equals("")) { btn. set. Text(x. Turn ? "X" : "O"); x. Turn = !x. Turn; } } // end action. Performed } // end class Listener //******************* public static void main(String[] args) { new Tic. Tac. Toe(); } } // end class Tic. Tac. Toe get. Source's return type is Object. The JButton cast operator is necessary to prevent a compilation error.

Embedded Layout Managers n n What layout manager scheme should be used for this

Embedded Layout Managers n n What layout manager scheme should be used for this mathcalculator window? The Grid. Layout manager is usually pretty good at positioning components in an organized tabular fashion, but it's limited by the fact that each of its cells must be the same size. 26

JPanel Class n n n A JPanel container object is a generic storage area

JPanel Class n n n A JPanel container object is a generic storage area for components. If you have a complicated window with lots of components, you may want to compartmentalize them by storing groups of components in JPanel containers are particularly useful with Grid. Layout and Border. Layout windows because each compartment in those layouts can store only one component. If you need a compartment to store more than one component, let that one component be a JPanel container, and put multiple components into the JPanel container. 28

JPanel Class n 29 When using a JPanel container, do these things: n n

JPanel Class n 29 When using a JPanel container, do these things: n n Since JPanel is in the javax. swing package, import that package. Instantiate a JPanel object: JPanel <JPanel reference> = new JPanel(<layout manager>) Optional argument. Default = Flow. Layout with center alignment. n Add the components to the JPanel object: <JPanel reference>. add(<component>) n Add the JPanel object to the window: add(<JPanel reference>)

JPanel Class n For example, to create the top-left cell's panel in the math-calculations

JPanel Class n For example, to create the top-left cell's panel in the math-calculations program, do this: n In the create. Contents method: x. Panel = new JPanel(new Flow. Layout(Flow. Layout. CENTER)); x. Panel. add(x. Label); x. Panel. add(x. Box); add(x. Panel); 30

This Math. Calculator program uses embedded layout managers to display square root and logarithm

This Math. Calculator program uses embedded layout managers to display square root and logarithm calculations. import javax. swing. *; import java. awt. event. *; public class Math. Calculator extends JFrame { private static final int WIDTH = 350; private static final int HEIGHT = 110; private JText. Field x. Box; // user's input value private JText. Field x. Sqrt. Box; // generated square root private JText. Field x. Log. Box; // generated logarithm //******************** public Math. Calculator() { set. Title("Math Calculator"); set. Size(WIDTH, HEIGHT); set. Default. Close. Operation(EXIT_ON_CLOSE); create. Contents(); set. Visible(true); } // end Math. Calculator constructor 31

Math. Calculator Program //******************* // Create components and add to window. private void create.

Math. Calculator Program //******************* // Create components and add to window. private void create. Contents() { JPanel x. Panel; // holds x label and its text box JPanel x. Sqrt. Panel; // holds "sqrt x" label and its text box JPanel x. Log. Panel; // holds "log x" label and its text box JLabel x. Label; JButton x. Sqrt. Button; JButton x. Log. Button; Listener listener; set. Layout(new Grid. Layout(2, 2)); // Create the x panel: x. Label = new JLabel("x: "); x. Box = new JText. Field(8); x. Panel = new JPanel(new Flow. Layout(Flow. Layout. CENTER)); x. Panel. add(x. Label); x. Panel. add(x. Box); 32

Math. Calculator Program // Create the square-root panel: x. Sqrt. Button = new JButton("sqrt

Math. Calculator Program // Create the square-root panel: x. Sqrt. Button = new JButton("sqrt x"); x. Sqrt. Box = new JText. Field(8); x. Sqrt. Box. set. Editable(false); x. Sqrt. Panel = new JPanel(new Flow. Layout(Flow. Layout. RIGHT)); x. Sqrt. Panel. add(x. Sqrt. Button); x. Sqrt. Panel. add(x. Sqrt. Box); // Create the logarithm panel: x. Log. Button = new JButton("log x"); x. Log. Box = new JText. Field(8); x. Log. Box. set. Editable(false); x. Log. Panel = new JPanel(new Flow. Layout(Flow. Layout. RIGHT)); x. Log. Panel. add(x. Log. Button); x. Log. Panel. add(x. Log. Box); // Add panels to the window: add(x. Panel); add(x. Sqrt. Panel); add(new JLabel()); // dummy component add(x. Log. Panel); 33

Math. Calculator Program listener = new Listener(); x. Sqrt. Button. add. Action. Listener(listener); x.

Math. Calculator Program listener = new Listener(); x. Sqrt. Button. add. Action. Listener(listener); x. Log. Button. add. Action. Listener(listener); } // end create. Contents //******************** // Inner class for event handling. private class Listener implements Action. Listener { public void action. Performed(Action. Event e) { double x; // numeric value for user entered x double result; // calculated value try { x = Double. parse. Double(x. Box. get. Text()); } catch (Number. Format. Exception nfe) { x = -1; // indicates an invalid x } 34

Math. Calculator Program if (e. get. Action. Command(). equals("sqrt x")) { if (x <

Math. Calculator Program if (e. get. Action. Command(). equals("sqrt x")) { if (x < 0) get. Action. Command { x. Sqrt. Box. set. Text("undefined"); retrieves the label of the } button that was clicked. else { result = Math. sqrt(x); x. Sqrt. Box. set. Text(String. format("%7. 5 f", result)); } } // end if else // calculate logarithm { if (x < 0) { x. Log. Box. set. Text("undefined"); } else { result = Math. log(x); x. Log. Box. set. Text(String. format("%7. 5 f", result)); } 35

Math. Calculator Program } // end else } // end action. Performed } //

Math. Calculator Program } // end else } // end action. Performed } // end class Listener //******************* public static void main(String[] args) { new Math. Calculator(); } // end main } // end class Math. Calculator 36

JText. Area Component n 37 The JLabel component works great for displaying a single

JText. Area Component n 37 The JLabel component works great for displaying a single line of text. But for displaying multiple lines of text, you should use a JText. Area component JCheck. Box component

JText. Area Component n To create a JText. Area component, call the JText. Area

JText. Area Component n To create a JText. Area component, call the JText. Area constructor like this: JText. Area <JText. Area reference> = new JText. Area(<display text>); n The display-text is the text that appears in the JText. Area component. If the display-text argument is omitted, then the JText. Area component displays nothing. 38

JText. Area Component n The JText. Area class, like all the GUI component classes,

JText. Area Component n The JText. Area class, like all the GUI component classes, has quite a few methods. Here are the API headings and descriptions for some of the more popular JText. Area methods: String get. Text() Returns the text area's text. void set. Text(String text) Assigns the text area's text. void set. Editable(boolean flag) Makes the text box editable or non-editable. void set. Line. Wrap(boolean flag) Turns line wrap on or off. void set. Wrap. Style. Word(boolean flag) Specifies whether word boundaries are used for line wrapping. 39

JText. Area Component private void create. Contents() { JText. Area license; JCheck. Box confirm.

JText. Area Component private void create. Contents() { JText. Area license; JCheck. Box confirm. Box; This code creates the components in the previously shown license agreement window. set. Layout(new Border. Layout()); license = new JText. Area( "SOFTWARE END-USER LICENSE AGREEMENTnn" + "READ CAREFULLY: This Software End-User License Agreement" + " is a legal agreement between us, the software provider, and" + " you, the end user of a software product legitimately" + " purchased from us. You must accept this agreement to" + " complete the sale of the software license. If you do not" + " accept this agreement, you forfeit all rights to your" + " current and future property and progeny. "); license. set. Editable(false); license. set. Line. Wrap(true); license. set. Wrap. Style. Word(true); confirm. Box = new JCheck. Box( "I accept the terms of this agreement. ", true); add(license, Border. Layout. CENTER); add(confirm. Box, Border. Layout. SOUTH); } // end create. Contents 40

JCheck. Box Component n JCheck. Box component interface: n n n A JCheck. Box

JCheck. Box Component n JCheck. Box component interface: n n n A JCheck. Box component displays a small square with a label to its right. When the square is blank, the check box is unselected. When the square contains a check mark, the check box is selected. Users click on the check box in order to toggle it between selected and unselected. 41

JCheck. Box Component n To create a JCheck. Box component, call the JCheck. Box

JCheck. Box Component n To create a JCheck. Box component, call the JCheck. Box constructor like this: JCheck. Box <JCheck. Box-reference> = new JCheck. Box(<label>, <selected>); n n The label argument specifies the text that appears at the right of the check box's square. If the label argument is omitted, then no text appears at the right of the check box's square. The selected argument specifies whether the check box is initially selected. If the selected argument is omitted, then the check box is initially unselected. 42

JCheck. Box Component n Here are the API headings and descriptions for some of

JCheck. Box Component n Here are the API headings and descriptions for some of the more popular 6 methods: boolean is. Selected() Returns true if the check box is selected and false otherwise. String set. Visible(boolean flag) Makes the check box visible or invisible. void set. Selected(boolean flag) Makes the check box selected or unselected. void set. Enabled(boolean flag) Makes the check box enabled or disabled. void add. Action. Listener(Action. Listener listener) Adds a listener to the check box. 43

JCheck. Box Component n Installation Options Example: 44

JCheck. Box Component n Installation Options Example: 44

JCheck. Box Component n n With a standard JButton button, you'll almost always want

JCheck. Box Component n n With a standard JButton button, you'll almost always want to have an associated listener. However, you may or may not want to have an associated listener for a check box. n n Use a listener if you want something to happen immediately, right when the user checks or unchecks the check box. If there's no listener, then the check box simply serves as an input entity. If that's the case, then the check box's value (checked or unchecked) would typically get read and processed when the user clicks a button. 45

JRadio. Button Component n JRadio. Button component interface: n n n n A JRadio.

JRadio. Button Component n JRadio. Button component interface: n n n n A JRadio. Button component displays a small circle with a label to its right. When the circle is blank, the radio button is unselected. When the circle contains a large dot, the radio button is selected. Almost always, radio buttons come in groups. Within a radio-button group, only one radio button can be selected at a time. If an unselected button is clicked, the clicked button becomes selected, and the previously selected button in the group becomes unselected. If a selected button is clicked, no change occurs (i. e. , the clicked button remains selected). 46

JRadio. Button Component n To create a JRadio. Button component, call the JRadio. Button

JRadio. Button Component n To create a JRadio. Button component, call the JRadio. Button constructor like this: JRadio. Button <JRadio. Button reference> = new JRadio. Button(<label>, <selected>); n n n The label argument specifies the text that appears at the right of the radio button's circle. If the label argument is omitted, then no text appears at the right of the radio button's circle. The selected argument specifies whether the radio button is initially selected. If the selected argument is omitted, then the radio button is initially unselected. This example shows how we created the standard and custom radio buttons in the installation-options program: standard = new JRadio. Button("Standard (recommended)", true); custom = new JRadio. Button("Custom"); 47

JRadio. Button Component n To enable the only-one-button-selected-at-a-time functionality of a radio button group,

JRadio. Button Component n To enable the only-one-button-selected-at-a-time functionality of a radio button group, create a Button. Group object and add individual radio button components to it. Here's how: Button. Group <Button. Group reference> = new Button. Group(); <Button. Group reference>. add(<first button in group>); . . . <Button. Group reference>. add(<last button in group>); n This example shows how we created the radio button group for the standard and custom radio buttons in the installation-options program: Button. Group rb. Group = new Button. Group(); rb. Group. add(standard); rb. Group. add(custom); 48

JRadio. Button Component n Here are the API headings and descriptions for some of

JRadio. Button Component n Here are the API headings and descriptions for some of the more popular JRadio. Button methods: boolean is. Selected() Returns true if the radio button is selected and false otherwise. String set. Visible(boolean flag) Makes the radio button visible or invisible. void set. Selected(boolean flag) Makes the radio button selected if the argument is true. Does nothing if the argument is false. void set. Enabled(boolean flag) Makes the radio button enabled or disabled. void add. Action. Listener(Action. Listener listener) Adds a listener to the radio button. 49

JCombo. Box Component n n n A combo box allows the user to select

JCombo. Box Component n n n A combo box allows the user to select an item from a list of items. Combo boxes are sometimes called drop-down lists because when you click the combo box's down arrow, a list of selection items drops down. After a selection is made, the item list disappears and only the selected item is displayed. Combo boxes are called "combo boxes" because they are a combination of a text box (normally, they look just like a text box) and a list (when the down arrow is clicked, they look like a list). Combo boxes and radio-button groups are similar in that they both allow the user to select one item from a list of items. But a combo box takes up less space on the window. So if you have a long list of items to choose from, and you want to save space, use a combo box rather than a group of radio buttons. 50

JCombo. Box Component n Note this example where the user selects a day from

JCombo. Box Component n Note this example where the user selects a day from among the five week days: 1. Initial display: 3. After user clicks on Thursday: 2. After user clicks on down arrow: 51

JCombo. Box Component n How to implement a combo box: 1. Create an array

JCombo. Box Component n How to implement a combo box: 1. Create an array of list options: private String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; 2. Create a combo-box object by passing the array to the JCombo. Box constructor: JCombo. Box days. Box = new JCombo. Box(days); 52

JCombo. Box Component n Here are the API headings and descriptions for some of

JCombo. Box Component n Here are the API headings and descriptions for some of the more popular JCombo. Box methods: void set. Visible(boolean flag) Makes the component visible or invisible. void set. Editable(boolean flag) Makes the combo box's top portion editable or non-editable. Object get. Selected. Item() Returns the item that is currently selected. void set. Selected. Item(Object item) Changes the currently selected item to the item that's passed in. void add. Action. Listener(Action. Listener listener) Adds a listener to the combo box. 53

Job Application Example n The upcoming program implements a job application by using check

Job Application Example n The upcoming program implements a job application by using check boxes, radio buttons, and a combo box for input and dialog boxes for output. This appears when user enters "good" values. This appears when user enters "bad" values. 54

Job Application Example import javax. swing. *; java. awt. event. *; javax. swing. border.

Job Application Example import javax. swing. *; java. awt. event. *; javax. swing. border. *; // for Empty. Border public class Job. Application extends JFrame { private static final int WIDTH = 250; private static final int HEIGHT = 300; private JCheck. Box java; // Java Sun certified? private JCheck. Box help. Desk; // help-desk experience? private JCheck. Box coffee; // good coffee maker? private JRadio. Button good. Citizen, criminal; private JCombo. Box salary; private String[] salary. Options = {"$20, 000 -$59, 000", "$60, 000 -$100, 000", "above $100, 000"}; private JButton submit; // submit the application //******************** public Job. Application() { set. Size(WIDTH, HEIGHT); set. Title("Job Application Form"); set. Default. Close. Operation(EXIT_ON_CLOSE); create. Contents(); set. Visible(true); } // end Job. Application constructor 55

Job Application Example //******************* // Create components and add to window. private void create.

Job Application Example //******************* // Create components and add to window. private void create. Contents() { Button. Group radio. Group; // Need window. Panel for south-panel separation and outer margin. JPanel window. Panel = new JPanel(new Border. Layout(0, 10)); window. Panel. set. Border(new Empty. Border(10, 10, 10)); // center. Panel holds all components except button JPanel center. Panel = new JPanel(new Grid. Layout(11, 1)); // Need a panel for button so it can be center aligned JPanel south. Panel = new JPanel(new Flow. Layout()); Without this line, our Grid. Layout components would touch the left edge of the window. The set. Border call allows us to specify a border. The Empty. Border class allows us to specify widths (in pixels) for the top, left, bottom, and right margins, respectively. The Empty. Border class is in the javax. swing. border package, so import that package. 56

Job Application Example java = new JCheck. Box("Java Sun certified"); help. Desk = new

Job Application Example java = new JCheck. Box("Java Sun certified"); help. Desk = new JCheck. Box("help-desk experience"); coffee = new JCheck. Box("able to make good coffee"); good. Citizen = new JRadio. Button("law-abiding citizen"); criminal = new JRadio. Button("violent criminal"); radio. Group = new Button. Group(); radio. Group. add(good. Citizen); radio. Group. add(criminal); salary = new JCombo. Box(salary. Options); submit = new JButton("Submit"); submit. add. Action. Listener(new Button. Listener()); center. Panel. add(new JLabel("Skills (check all that apply): ")); center. Panel. add(java); center. Panel. add(help. Desk); center. Panel. add(coffee); center. Panel. add(new JLabel()); // filler center. Panel. add(new JLabel("Community standing: ")); center. Panel. add(good. Citizen); center. Panel. add(criminal); center. Panel. add(new JLabel()); // filler center. Panel. add(new JLabel("Salary requirements: ")); center. Panel. add(salary); 57

Job Application Example window. Panel. add(center. Panel, Border. Layout. CENTER); south. Panel. add(submit); window.

Job Application Example window. Panel. add(center. Panel, Border. Layout. CENTER); south. Panel. add(submit); window. Panel. add(south. Panel, Border. Layout. SOUTH); add(window. Panel); } // end create. Contents //******************** // Read entered values and display an appropriate message. private class Button. Listener implements Action. Listener { public void action. Performed(Action. Event e) { if ( (java. is. Selected() || help. Desk. is. Selected() || coffee. is. Selected()) && (good. Citizen. is. Selected()) && (!salary. get. Selected. Item(). equals("above $100, 000"))) { JOption. Pane. show. Message. Dialog(null, "Thank you for your application submission. n" + "We'll contact you after we process your information. "); } 58

Job Application Example else { JOption. Pane. show. Message. Dialog(null, "Sorry, no jobs at

Job Application Example else { JOption. Pane. show. Message. Dialog(null, "Sorry, no jobs at this time. "); } } // end action. Performed } // end class Button. Listener //******************* public static void main(String[] args) { new Job. Application(); } } // end class Job. Application 59