CS351 Spring 2004 Lab 10

Swing: The Basics


Some JComponent Manipulation

JTextField balj

JComponents

The basic GUI widget are represented by subclasses of JComponent. The Java Swing Trail provides a handy Visual Index to Swing Components

The basic procudure to add a JComponent to a pane, is to instantiate it and then add it to the ContentPane of the container that you want to add it to:

	JButton button = new JButton("Click Me!");
	this.getContentPane().add(button);

The basic JComponents:

  • JPanel - a container into which JComponents can be placed, each has its own layout
  • JLabel - provides for uneditable text and/or image
  • JButton - provides a basic button with a JLabel embedded in it
  • JRadioButton - one of group of button, only one of which can be selected
  • JTextField - a basic field for entry/display of text
  • JTextArea - multi-line area for text entry/display (handy for console-like display)

Layout Managers

Layout managers determine who components are laid out inside of a container. Again, the Java Swing Tutorial provides a Visual Guide

To use a Layout manager, we use the setLayout method on the Pane we want to control:

	this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
This example well tell the JFrame to layout the components in vertical line, by default, centered.

This is generally done before adding components. Note that with most layout managers, the order in which you add components effect how they are placed into the container.

The basic LayoutManagers that you should get the hang of:

  • FlowLayout - just lays things out one after another, wrapping as needed, the default for most containers. Takes no arguments
  • BoxLayout - put components in a line (vertical or horizontal). Takes a reference to object being laidout and constant BoxLayout.Y_AXIS or BoxLayout.X_AXIS telling it which direction to put things
  • GridLayout - lays things out in a uniform grid. Takes two number specifying the dimensions of the grid (in number of components), one of the two may be zero, telling it to grow in that direction as needed.
Exercise

Create a dummy GUI as shown in this screenshot:

Hint: This can be done by combining about six JPanels using BoxLayout, consider using GridLayout.

While many IDE provide GUI builders which are very helpful, and you are encouraged to use them in general. Do this exercise by hand, even with a good GUI builder, you need to be able to understand what it's doing.

For Monday, Due Wednesday 5PM
For Wednesday, Due Friday 5PM