Chapter 7 - User Interface
The Abstract Windowing Toolkit
The Abstract Windowing Toolkit is a Java package that handles most user interface components. This includes menus, buttons, checkboxes, scrollbars, and windows which allows the user to interact with your applet. The AWT also directly handles events which tell the applet that something has happened. An event could be a mouse click, a key press, or simply a movement of the window.
The AWT also handles how these components are positioned and displayed in the browser window. Unlike many other programming languages, Java only gives you abstract ways to control the layout of your components. This is necessary because your Java applet will be run on many different platforms, with many different monitor sizes, and many different resolutions.
To control the layout of your user interface components you use containers. Containers are objects that can contain UI components or other containers. The panel container is simply a container that is viewed on screen and is actually what you have been drawing to all along. Canvases are like panels but are suited for displaying graphics or drawings.
The user interface components are placed inside containers. To implement a UI component you first need to create it and then add it to the appropriate panel. This is a simple process and will be shown for the different UI components available in Java.
Layout managers
Under Construction...
Labels
The simplest UI component is the label. Labels are short strings that describe or label other UI components, such as buttons, in the given panel. You should always use labels rather than simple text strings in your GUI because the label component aligns itself with the rest of the panel and does not have to be redrawn.
Label() creates an empty label Label(String) creates a label with the given text Label(String, int) creates a label with a different alignmentThe Label() constructor defaults to aligning the text on the left but this behavior can be changed by using the third constructor. The integer that follows the string argument can take certain values to change the justification of the label. Left alignment is 0, center alignment is 1, and right alignment is 2 or you can use the provided instance variables Label.LEFT, Label.CENTER, and Label.RIGHT.
To add the label to the current panel use the add method.
add(new Label("OK Button")); add(new Label("Reset Button",1)); add(new Label("Cancel Button", Label.RIGHT));You can check or modify the attributes of the label using the provided methods.
getAlignment() returns the integer describing the alignment setAlignment(int) sets the alignment to the specified value getText() returns a string with the label's text getText(String) changes the label to the given string
Text fields
Text fields are small boxes that allow the user to enter text into the applet. It is a good idea to label your text fields with the label component to insure the user is inputting the text you expect.
TextField() creates an empty text field with width 0 TextField(int) creates an empty text field with width given TextField(String) creates text field with given string and width 0 TextField(String, int) creates text field with given string and widthWhen you add text fields to your panel you can set them to act like password fields which do not show the text that is being typed by the user. To do this, you first create the field and then set the character that will be echoed to the screen when the user types a character into the field.
add(new Label("Username: ")); add(new TextField(30)); add(new Label("Password: ")); TextField passwordField = new TextField(30); passwordField.setEchoCharacter('¥'); add(passwordField);Text fields have a variety of methods to set or check attributes.
getText() returns string with the text in the field setText(String) set the text in the field to the given string select(int, int) selects the text between the two positions selectAll() selects all the text in the field getColumns() returns the width of the field getEchoChar() returns the character used for echoing setEchoCharacter(char) sets the character for echoing appendText(String) adds the given string to the end of the field getSelectedText() returns the selected text as a string getSelectedStart() returns the position of the start of the selection getSelectedEnd() returns the position of the end of the selection isEditable() returns whether the field is editable setEditable(boolean) sets whether the field is editable
Text areas
Text areas are similar to text fields but can handle more text because they can have multiple rows and scrollbars. Much of their behavior is identical to text fields.
TextArea() creates empty text area with dimensions of 0,0 TextArea(int, int) creates empty text area with given dimensions TextArea(String) creates text area containing the given string TextArea(String,int,int) creates text area with given string and dimensions TextArea textBox = new TextArea("Four score and seven years ago...", 50, 60); add(textBox);When creating the string to include in the text area, it is important to remember the escape sequences. You cannot put in a double quote mark because Java would think that was the end of the string in the Java code. To actually include a double quote mark in the component you need to precede it with a backslash. The backslash tells Java that the following character is to be treated as special. Also, remember the formatting codes such as \n which is a newline character.
Text areas support most of the same methods that are supported by text fields with the following additions.
getRows() returns the number or rows in the text area insertText(String, int) inserts the given string at the given position replaceText(String, int, int) replaces the text between the given positions with the given string appendText(String) adds the given string to the end of the area getSelectedText() returns the selected text as a string getSelectedStart() returns the position of the start of the selection getSelectedEnd() returns the position of the end of the selection isEditable() returns whether the area is editable setEditable(boolean) sets whether the area is editable
Checkboxes
Checkboxes can be selected by users and serve as a way to present a series of option to users. Each checkbox is either checked or not checked at any given time. Checkboxes can be used in two different ways depending on what kind of input you want from the user. Nonexclusive checkboxes are a series of checkboxes in which any number can be selected at any one time. Exclusive checkboxes are a series of checkboxes where only one can be selected at once. Exclusive checkboxes are often called radio buttons.
Checkbox() creates empty checkbox Checkbox(String) creates checkbox with label given by string Checkbox(String,null,boolean) creates a checkbox with given label and in the given checked/unchecked state. Checkbox(String,CheckboxGroup,boolean) creates a checkbox with the given label, belonging to the given group, and with the given stateThe last two constructors have three arguments of which the boolean argument determines if the box is checked or not. If you pass the value of true, the box will be checked when it is created. The second argument is a group variable used in exclusive checkbox groups. If it is set to null it is ignored.
Nonexclusive example:
add(new Checkbox("Computer", null, true)); add(new Checkbox("Monitor", null, true)); add(new Checkbox("Printer")); add(new Checkbox("Modem")); add(new Checkbox("Keyboard", null, true));Exclusive example (radio buttons):
CheckboxGroup name = new CheckboxGroup(); add(new Checkbox("Matt", name, true)); add(new Checkbox("Bob", name, false)); add(new Checkbox("Deena", name, false)); add(new Checkbox("Cheryl", name, false)); add(new Checkbox("Other", name, false));Checkbox methods are the same for both types.
getLabel() returns the label of a checkbox as a string setLabel(String) sets the label of a checkbox to the given string getState() returns true if the checkbox is checked or false if it is not checked setState(boolean) set the checkboxes state to checked or uncheckedExclusive checkboxes have four additional methods.
getCheckboxGroup() returns the checkbox group of the given checkbox setCheckbocGroup(CheckboxGroup) sets the checkbox group of a checkbox getCurrent() returns the selected checkbox setCurrent(CheckBox) sets the selected checkbox to the one given
Buttons
Buttons are UI components that trigger an action in your applet when the user presses them. You do not need to label buttons because you can put text on the face.
Button() creates a button with no label on its face Button(String) creates a button with the given labelYou can access and change the text of the button by using the following methods.
getLabel() returns a string with the label of the button setLabel(String) changes the label of the button to the stringAdding and using buttons is very simple. Later you will learn how to respond to a user clicking on the button you provide which is a certain type of event.
add(new Button("OK")); add(new Button("Reset")); add(new Button("Cancel"));
Popup choice menus
Choice menus display a list of options when clicked and let the user select the appropriate option. The menu will then display the user's choice. Choice menus only allow the selection of one item like exclusive checkboxes or radio buttons.
To create a choice menu you first declare an instance of the class choice and then add menu items to that instance.
Choice nameMenu = new Choice(); nameMenu.addItem("Matt"); nameMenu.addItem("Bob"); nameMenu.addItem("Deena"); nameMenu.addItem("Cheryl"); nameMenu.addItem("Other"); add(nameMenu);The methods available to access and modify choice menus are as follows.
addItem(String) adds the string as an item to the menu getItem(int) returns the string of the item at the given position countItems() returns the number of items getSelectedIndex() returns the position of the selected menu item getSelectedItem() returns the string of the selected item select(int) selects the item at the given position select(String) selects the item with the given stringRemember that the positions in the menu start with 0 like the positions in an array. Choice menus are often useful when you want to provide a variety of options but need to keep the screen space required to a minimum.
Scrolling lists
Scrolling lists are similar to choice menus but they allow the user to select more than one option like nonexclusive checkboxes. Scrolling lists can optionally be defined to only accept a single option at one time.
To create a scrolling list you need to first create an instance of the class List and then add items to that instance. The first value in the List constructor is how many lines should be visible at once. The second determines whether the user will be allowed to select multiple items at a time.
List computerList = new List(3, true); computerList.addItem("Computer"); computerList.addItem("Monitor"); computerList.addItem("Printer"); computerList.addItem("Modem"); computerList.addItem("Keyboard"); add(computerList);The available methods to access and modify scrolling lists follow.
getItem(int) returns string of the item at the given position countItems() counts the items in the list getSelectedIndex() returns the position of selected item (for exclusive lists) getSelectedIndexes() returns an array containing the positions of the selected items (for nonexclusive lists) getSelectedItem() returns the string of the selected item (for exclusive lists) getSelectedItems() returns an array of strings of the selected items (for nonexclusive lists) select(int) selects the item at the given position deselect(int) deselects the item at the given position select(String) selects the item with the given string isSelected(int) returns true if the given position is selected delItem(int) deletes the item in the given position delItems(int, int) deletes the items between the given positions replaceItem(String, int) replaces the item at the given position with the given string setMultipleSelections(boolean) sets whether the list should allow multiple selections
Sliders
Sliders are scrollbars that are not attached to any UI component and let the user select a value from a range of values. There are three constructors for sliders.
Scrollbar() creates a vertical scrollbar with 0 as min and max values Scrollbar(int) creates a scrollbar with 0 as min and max values and the given alignment Scrollbar(int, int, int, int, int) creates a scrollbar with the given alignment, initial set value, the page size, initial min value, and initial max value Scrollbar slider1 = new Scrollbar(Scrollbar.HORIZONTAL, 30, 10, 1, 100); add(slider1);The alignment value is 0 for vertical and 1 for horizontal. You may also use the variables Scrollbar.VERTICAL and Scrollbar.HORIZONTAL. The initial set value should be between the minimum and maximum values given to the slider. The page size is how much the slider will skip when the user clicks inside the scrollbar.
A more interesting example is the Slider2Demo class which contains a label for the minimum and maximum values. It also updates the current value shown when the user clicks on the slider. You will learn about handling events in Chapter 8.
import java.applet.*; import java.awt.*; public class Slider2Demo extends Applet { Label currentLabel; Scrollbar slider1; public void init() { resize(300, 100); setLayout(new FlowLayout(FlowLayout.LEFT)); add(new Label("1")); slider1 = new Scrollbar(Scrollbar.HORIZONTAL, 30, 10, 1, 100); add(slider1); add(new Label("100")); add(new Label("The current value: ")); currentLabel = new Label("30"); add(currentLabel); } public boolean handleEvent(Event e) { if (e.target instanceof Scrollbar) { int current = slider1.getValue(); currentLabel.setText(String.valueOf(current)); } return true; } }The scrollbar class has a series of methods for accessing and modifying its attributes.
getMaximum() returns the max value of the slider getMinimum() returns the min value of the slider getOrientation() returns 0 for vertical and 1 for horizontal getValue() returns the current value of the slider setValue() sets the current value of the slider
showStatus()
The showStatus() method, while not a UI component, is useful when you want to communicate with the user. It displays the passed string in the status area of the browser or enclosing application. In Netscape Navigator, it displays the message in the lower left border of the window.
import java.applet.*; import java.awt.*; public class StatusDemo extends Applet { String message = "You just clicked on me..."; public void init() { resize(300, 100); } public boolean mouseDown(Event e, int x, int y) { showStatus(message); repaint(); return(true); } }The StatusDemo applet displays the message "You just clicked on me..." in the status area when the user clicks in the area of the applet.
It is often a good idea to mimic the normal use of the status area when programming your applets. For instance, when creating an applet that links to another document you should show the URL of the destination in the status area like the browser normally does with hypertext links. You could also give progress indications or help messages.