CS 3230 - Chap 9 Notes

Swing GUI Controls

Here comes the coup de grace of GUI programming: all the widgets you could ever want. You can see a demo of all of these by navigating to

	j2sdk[ver]/demo/jfc/SwingSet2/
and then run the demo by typing
	java -jar SwingSet2.jar
Be sure to look at the "Source Code" tabs on all of the demo pages to see how they did it.

In these notes, I'll show you some additional, useful controls that the book doesn't discuss.

Model-View (p.336)

Many of the Java GUI controls use this design pattern. Basically, what it means is that you have one class that is responsible for displaying the data (just as a combo box, list, tree, or table) and another class that is responsible for holding the data. Thus, rather than making a combo box like so:

ComboBox combo = new ComboBox();
combo.add("Red");
combo.add("Yellow");
combo.add("Blue");
combo.add("Green");
you instead say:
String[] comboItems = { "Red", "Yellow", "Blue", "Green", };
final JComboBox combo = new JComboBox(comboItems);

In the case of more sophisticated controls like the JTree and JTable, you can create a "data" class that implements the TreeModel interface or the TableModel interface which the control will use to find out how to get its data. (More on this below.)

The GUI Control Zoo

Space-Saving Components

These components were designed to help you make better use of the screen real estate.

JTabbedPane - Gives you little tabs along the top, treat each tabbed pane as a container. (Commonly found in dialogs).

JScrollPane - Gives you scrollbars around another component that is too large to display in the given area. A large image could be placed in a scroll panel.

JSplitterPane - Gives you a movable split bar between two other containers.

Text Components (p.350)

Text Field (p.350) - one-line text entry control.

Password Field (p.356) - as above, but echoes asterisks instead of the characters typed.

Text Area (p.371) - multi-line text entry control

Source code: TextExamples.java - shows the above text fields. Note that this example also shows how to use two space-saving components: the JTabbedPane and the JScrollPane.

Selecting / Editing (p.376) TextEditTest.java - From your book, p.376. Shows how to respond to Action events generated by text fields. Also shows how do a search and replace in a text area.

Choice / Selection GUI controls (p.378)

One advantage that GUI programs have over CLI programs is that they can constrain user choices (hopefully constraining them to only valid choices).

Check Box (p.378) - Boolean on/off GUI control, accompanied by a label, typically displayed as square boxes.

Radio Button (p.381) - Mutually exclusive group of check boxes, accompanied by labels, typically displayed as circles.

Source Code: CheckRadioExamples.java - shows both of the above controls. Also shows how you can test to see if / which items are selected.

Combo Boxes (p.389) - Single-choice control that shows a drop-down list of available choices.

List Boxes - Multi-choice control, that displays all choices in a list. If you want scrollbars, wrap it in a JScrollPane.

Source Code: ComboAndList.java - shows both of the above controls. Also, shows how to listen for events. Note that we use an array of strings for the "model" here (the combo and list controls are the "view").

Slider (p.392) - Where the combo box lets us pick from a list of values, the slider lets us pick a value along a continuous range, similar to a horizontal volume control on a radio. See SliderTest.java from your book on p.394.

Spinner (p.389) - Think of this as kind of a cross between a combo box and a slider control: we get to pick a value, typically from a range, but it is presented as a text box with up/down buttons on one side. See SpinnerTest.java from your book on p.400. You will have to deal with model / view here.

Sophisticated Swing Controls

JTree - Displays selections as a root node, branches, and leaf nodes. See TreeExample.java. Note that I am getting around using the model / view approach here, illustrating that you don't have to use it if you don't want to.

JTable - Displays tabular data. Suitable for a spreadsheet or database application. See TableExample.java. Note the use of the AbstractTableModel class (an anonymous, inner class) to supply the table with data. We could use the JTable to display data in a database table by putting the appropriate SQL code in the table model class.

For an example of how a JTable could be used to show the contents of a database table, look at QueryTable.java. Uses the Access database books.mdb.

JEditorPane - Similar to the JTextArea, this control can display plain text, HTML, or RTF (Rich Text Format) files. See Lab8_starter.java. (You'll enhance this program for your Lab 8 exercise.

Menus and Toolbars (p.406)

"Menus" as GUI controls are some of the oldest user interface components, designed after the idea of a menu you get in a restaurant. They were first seen in the Lotus123 spreadsheet program (text-ui). Toolbars followed some years later as an alternative to menus, allowing the user to quickly perform frequently-used menu operations with a single click.

Toolbars are a series of buttons linked to commonly-used menu commands. They were invented to make it quicker for the user to get things done. Toolbars manage their own buttons / placement / positioning / etc.; you do not have to do much of the work by hand.

Various Menu Components

JMenuBar (p.406) - Long strip of selections at the top of the frame. Call JFrame.setJMenuBar() to put it on the top of the screen -- This is so you still have the North part of your BorderLayout avaiable to hold the toolbar.

JMenu (p.406) - Selection of items.

JMenuItem (p.407) - Specific entry on a menu. On p.408 in your book it shows an alternate constructor you can use to give your menu items cute little icons next to them.

Sub-menu - Additional menu that pops-up when a particular menu item is highlighted. It is possible to add a JMenu in place of a JMenuItem in another JMenu because JMenu is derived from JMenuItem. (Tricky, eh?)

Check box / Radio button menu items (p.410) - A rich, savory blend of GUI controls and menu components. You use the ButtonGroup class to create the mutual-exclusion behavior, just like you do with the JRadioButton controls.

JPopupMenu (p.411) - Also called "context menus", pop-ups are little, stand-alone menus that are usually activated by right-clicking the mouse somewhere in the app. Note that you add popup menus using the add() method of the JComponent class. The implication here is that each component in your app can have its own popup menu. On p.412 in your book it talks about how you can use the isPopupTrigger() method of the MouseEvent class to test whether a mouse click indicates that a popup menu should be displayed for the particular platform your app is running on.

Accelerators (p.412) - You can tie a keystroke to a menu item by calling the setAccelerator() method. Example on p.413.

Source code: MenuTest.java - From your book on p.416. Demonstrates all of the above menu components. Note how the "Save" / "Save As" items become disabled when you select the "Read Only" checkbox menu item. Note also the use of "seperators" to create logical groupings of related items.

Toolbars (p.419)

Toolbar (p.419) A sequence of buttons, often seperated into groups. These can often be repositioned by grabbing the little grippy thinger (called the "gripper") on the left.

Tooltips (p.421) Li'l text boxes that appear when you float the mouse over a button. You can actually give any component a tooltip by calling the setToolTipText() method of the Component class.

Source code: ToolBarTest.java From your book on p.422. Note that this example uses the Action interface to make both the menu items and the toolbar buttons work.

Even More Layout Managers

Back in the chapter 7 notes I introduced you guys to layout managers. Here's a few more layout managers you can use.

Grid (p.346) - A layout manager that displays rows and columns of data. Examples of apps that use a grid-type layout: most calculator programs and the "Minesweeper" game. A Checker / Chess/ Go board could be represented with a Grid layout. See GridLayoutExample.java.

Cute trick: If you want to make a "vertical" version of the flow layout, you can just make a new grid layout with 0 rows and 1 column. Both rows and columns will expand by default to hold more components so you can add N number of controls. However, only 1 row will be created because you specified a 0 (magic number) for the rows.

Box (p.426) - An alternative to the grid control. Can be either vertical or horizontal.

GridBag (p.430) - Intended as a more flexible version of the Grid control, allowing you to have components that span multiple cells. See GridBagLayoutExample.java. Note the use of the GridBagConstraints class to specify how cells will be spanned. Uses the file WindowCloser.java.

Spring (p.436) - Intended as an easier to use alternative to the GridBag layout. The jury is still out on whether this one is actually easier to use.

None (p.446) - Lastly, if you want to stop the insanity, you can just call setLayout(null) on the container, add your controls, and call setBounds(x, y, width, height) on the controls to position them. See SpaceGame.java as an example of how to use setSize() and setLocation() on a class derived from Component. Uses the image ship.png.

Custom (p.446) - For those real masochists out there, you can even write your own layout manager.

Dialogs

A dialog box is a container class that can hold GUI controls. (Since it is not a frame, it cannot hold menubars or toolbars.) They can be either:

Making your own Dialogs

On p.462-3 in your book it explains how to make your own, custom dialogs. The way you do it is very similar to the way you make a frame: in the constructor you select a layout manager and add controls to the content pane.

Owner: one important difference between dialogs and other containers (like frames, panels, applets, etc.) is that all dialogs must be passed an owner as a parameter to the constructor. The "owner" is the container that launched the dialog, such as a frame or another dialog. (See the API notes p.466.)

Data Exchange: (p.466) - To communicate between the owner frame and the dialog, you basically need to handle the action event sent by the button that closes the dialog and extract the relevant information there. P.468 in your book shows a somewhat convoluted example of how to do that.

Simple Canned Dialogs (p.452 bottom)

These are basic dialog boxes you can use to display a message, get a confirmation (yes / no) or ask for a single line of input. See the bulleted list at the bottom of p.452 for the various types.

Source code: OptionDialogTest.java from your boo on p.455. Illustrates how to use the various static methods of the JOptionPane class to construct and display simple dialogs.

Sophisticated Canned Dialogs (p.473)

The following pre-built dialogs are available for your use. You can see them in the "SwingSet2" demo.

JFileChooser (p.473) - Dialog that shows files in the current directory and allows you to navigate to other parts of the file system. P.478 shows how you can make a preview window to display image files.

JColorChooser (p.483 bottom) - Allows the user to pick a color. Screenshots on p.484. Code snippet on p.485 shows how you can retrieve the selected color after the user clicks "OK".