CS136, Lecture 4

    1. Java GUI components
      1. Buttons
    2. Event-driven programming in Java
    3. Other GUI components
      1. Labels
      2. Text Fields
      3. TextAreas
      4. Choice buttons
      5. Other GUI components:
    4. Layout managers
      1. FlowLayout
      2. BorderLayout
      3. GridLayout
      4. Mixing layouts
        1. Panels
        2. Canvases

Java GUI components

Include labels, text fields, buttons, etc. (all part of java.awt)

Advantage of components over graphics objects is that they are automatically redrawn during repaint. Need not explicitly put in commands to draw them!


Buttons

For example, Button is class of buttons.

Constructor is:

	public Button(String label);
when executed creates a button with "label" printed on it. Generally large enough to display label.

Responds to variety of messages. One of most useful is

	public void setBackground(Color buttonColor);
which changes color of button.

Color is predefined class with many constants representing colors:

Can also create own new colors with Color constructor (see documentation)

Add a button to an applet by writing:

    add(startButton);
This will normally result in button being added to applet in first available space starting from top left and working across from left to right (and then trying next row, etc.)

Button generates an event when user clicks on it.

Event-driven programming in Java

Usually programs based on interaction with user through pressing buttons, mouse clicks or drags, key presses, etc.

Method "action" is executed whenever there is an event (and no other routine executing)

	public boolean action(Event evt, Object obj);
Event has a number of fields which can be used to identify the kind of event. One of simplest things to do is to identify the object involved with the action by examining the "target" field.

E.g., if Button startButton = new Button("start");

then can write

    if (evt.target = startButton)
        doStart();
See program buttons for simple example.

Look at program bouncing ball to see use of button and graphics objects from library.

Other GUI components

Labels

Label is essentially a simplified version of DrawableString.

The constructors are

    public Label()          // creates label with no text
    public Label(String s)  //create label with text s
Methods
    public String getText()     // return label text
    public void setText(String s)   // sets the label text

Text Fields

TextField is a single line area that the user can type into. It is a good way of getting text input from the user.

The constructors are

    public TextField ()             // creates text field with no text
    public TextField (int columns) 
            // create text field with appropriate number of columns
    public TextField (String s) // create text field with s displayed
    public TextField (String s, int columns)
        // create text field with s displayed & appropriate width
Methods
    public void setEditable(boolean s)  
        // if false the TextField is not user editable
    public String getText()     // return label text
    public void setText(String s)   // sets the label text
When the user types into a text field and then hits the return or enter key, it generates an event which can be handled using the action routine.

Recall the action routine has declaration:

    public boolean action (Event evt, Object obj)
As with buttons, test to see if evt.target == myTextField. If so, can get contents from obj, which has type Object.

To be able to do anything with it, you must "downcast" obj to String.

Alternatively, you can get the contents of the field using getText().

TextAreas

TextArea is a class that provides an area to hold multiple lines of text. It is fairly similar to TextField.

The constructors are

	public TextArea (int rows, int columns) 
		// create text field with appropriate number of rows & columns
	public TextArea (String s, int rows, int columns) 
		// create text field with rows, columns, & displaying s
Methods
	public void setEditable(boolean s)	
		// if false the TextField is not user editable
	public String getText()		// return label text
	public void setText(String s)	// sets the label text
Unlike TextField, hitting return or enter does not generate an event.

See example Book (but ignore layout).

Choice buttons

Choice provides a list of items from which the user can make a selection.

The constructor is:

	public Choice()		// create new choice button
The most useful methods are:
	public void addItem(String s)	// add s to list of choices
	public int countItems()		// return # choices in list
	public String getItem(int index) // return item at index
	public String getSelectedItem() // return selected item
	public int getSelectedIndex() // return index of selected item
	
The user selecting an item is an event which is handled as usual with action.

Other GUI components:

Other components that we are less likely to use include checkboxes, radio buttons, lists, scroll bars, etc. Information on these can be found through the web page.

Layout managers

Layout managers help the programmer lay out components on the applet so that they look good even if the user changes the size of the applet.

FlowLayout

The default Layout manager for an applet is FlowLayout, which simply lays out items from left to right across the top of the applet. When there is no more space it starts a new row. Thus if an applets width is decreased, items from one row may move down to a lower row.

BorderLayout

The BorderLayout provides a bit more control over placement by allowing the programmer to add components into one of 5 areas: North, South, East, West, and Center.

BorderLayout has two constructors:

	public BorderLayout()
	public BorderLayout(int horizGap, int vertGap) 
					// leaves given gap size between components.
The layout manager of an applet can be changed to BorderLayout by executing:
	setLayout(new BorderLayout())
Components can be added by using a more refined version of add:
	add(String direction, Component comp)
Thus to add a button on the north, write
	add("North",startButton)
Note that all directions must begin with a capital letter or an error will occur.

Components added to "North" and "South" extend to the left and right edges of the Applet, while those added "East" and "West" extend up and down to the components to the "North" and "South". The component in the "Center" fills the remaining space.

If one component is omitted, other components stretch to fill that space.

With the BorderLayout, components stretch to fill all of the Applet. As a result using this by itself can often make layouts look distorted.

GridLayout

GridLayout arranges components into evenly spaced rows and columns. Constructors include:
	public GridLayout(int rows, int cols)  
	   // Construct layout w/ given rows and columns
	public GridLayout(int rows, int cols, int h, int v)  
	   // Construct layout w/ given rows and columns, and 
	   // horiz and vertical gaps of h and v between components
Executing
	setLayout(new GridLayout(2,3))
divides the applet into 2 rows and 3 columns. When "add" method is executed, components are added from left to right first across the first row, then second row, etc.

The only somewhat unfortunate thing about GridLayout is that all components added are resized to be exactly the same size.

Mixing layouts

Most of the time, none of the three layout managers described above does exactly what you want them to do. However, you can build up your applet from components called panels and canvases and then place the GUI components directly on those components.

Panels

A Panel is a type of container. GUI components can be added to a panel, which can itself be added to an applet (or indeed another Panel).

The constructor for a panel is:

	public Panel()

Canvases

A Canvas is a component on which graphics can be drawn and that can receive mouse events.

Its constructor is:

	public Canvas()
Both Panel and Canvas have method:
	public void resize(int width, int height)
Canvases must be resized or they will be set to have size (0,0) (and hence be invisible). You can try to resize panels, but the layout manager may stretch them to a somewhat different size.

The example program Book provides a good example of using panels and both FlowLayout and BorderLayout to lay out an applet nicely.

We'll see other examples later.