Designing a JAVA GUI
Basic User Interface Tasks:
- Provide help/guidance to the user.
- Allow input of information.
- Allow output of information.
- Control interaction between the user and device.
- Minimize the burden on the user (number of actions required,
number of things to remember)
- Minimize the number of components to perform a single task.
- Design for reuse!
Example Swing objects for input, output, control, guidance:
- Guidance: A JLabel displays a short string of text or an image.
It can serve as a prompt.
- Input: A JTextField allows editing of a single line of text. It
can get the user's input.
- Output: A JTextArea allows editing of multiple lines of text. It
can be used to get data or display results.
- Control: A JButton is an action control. By implementing the
ActionListener interface it will handle the user's action events.
Choosing the top level Window
- For applets, top-level window is JApplet.
- For applications, a JFrame is used.
- For popup dialog boxes JDialog is used.
- JApplet, JDialog, and JFrame are subclasses of Container and are
suitable for holding the interface components
More Swing Objects:
- JComponent
: Component objects provide the interaction between the user and the
interface. There are a multitude of classes built from JComponent, each
provides a different interface control. Some of the common ones are:
- JButton
: Creates a simple push button. It may have text or an icon on it. When
it is pressed an event is triggered and sent to owning frame.
- JTextField
: Creates a text entry box on the panel.
- JLabel
: Creates a label on the panel. A user entry area usually
consists of a JLabel followed by a JTextField.
- JTextArea
: creates an editable field that allows more than one line of text
- JScrollPane
: Special type of pane that allows vertical and horizontal scroll bars
to control the component inside it. You can add scroll bars to
JTextArea, JList, and JTable by first creating a scroll pane, then
placing the JTextArea, JList or JTable inside it.
- JCheckBox
: Creates a simple checkbox with a text title.
- JRadioButton
: Creates a radio button. Unless it is added to a ButtonGroup object it
will act independently of other radio buttons.
- ButtonGroup
: Creates an object that controls groups of buttons, allowing only one
to be selected at a given time.
- Canvas
: Creates an object that can be used to draw graphics with lines,
circles, rectangles, etc.
- JToolBar
: Creates a toolbar object to which buttons can be added.
- JMenuItem
: Creates a menu item object that can be added to a JMenu
- JMenu
: Creates a popup/pulldown menu containing JMenuItems.
- JMenuBar:
Contains JMenu items and displays them.
- Swing also provides complex controls like JTable
for the easy creation of spreadsheets, JOptionPane
for simple popup message boxes, FileDialog
and JFileChooser
to ask users for file names, and JTabbedPane
to create tabbed forms.
Creating a frame
- In order to implement a GUI interface in a JAVA application it
is necessary to first create a JFrame.
- The Frame is the object that is the master of all the
other interface objects. A JFrame controls what goes on the
banner/title line, the
open/close/minimize boxes. A JFrame has the ability to display one
Panel in
its content area. The Panel in turn displays components such as buttons
and
text boxes. The JFrame constructor would typically set its layout
manager and add components to its panel. By default, JFrame creates a
panel (referred to as a content pane).
- It is best to create a new class that extends JFrame, within its
constructor you can add the code to initialize the frame and to create
all
the components. In NetBeans you can do this by selected new-gui
forms-jframe.
- Java automatically sets the icon to a cup of coffee. If you
don't like this, then your frame can change it to something else by
first loading an image, then setting the image. To do this first create
an a URL object to hold the location of the image (you'll need to
import java.net.*), then create an ImageIcon object (named ic)
and load it with a gif picture. Finally, use the setIconImage
method (inherited from Frame) tell the frame to use the image. Note:
since the setIconImage method expects an object of type Image, then I
have to use the getImage method of ImageIcon (confusing? I thought so
too). The following code can be added to the constructor of your
JFrame class to change the icon (place this code right after the call
to initComponents();).
URL iconurl = getClass().getResource("logo.gif"); //
capitalization counts on the filename, file should be located with the
.java
files
ImageIcon ic = new ImageIcon(iconurl); // get file as an
imageicon
setIconImage(ic.getImage()); //
tell the frame to set is as its icon
- Also in the constructor you should add lines of code to set
the title , program size, and center it on the screen.
setTitle("My Application");
// sets the title in the blue banner bar
setSize(800,600); // sets the
size of the JFrame
setLocationRelativeTo(null); //centers application on the screen, must
go after setSize
- NetBeans places main routine in the same file.
Normally you will not have to modify the main routine
import java.net.*;
public class Test extends javax.swing.JFrame {
/** Creates new form Test */
public Test() {
initComponents();
setTitle("My Application");
setSize(800,600);
setLocationRelativeTo(null); // this statement must go after the set
size, centers application on the screen
URL iconurl =
getClass().getResource("logo.gif"); // capitalization counts on the
filename
ImageIcon ic = new ImageIcon(iconurl);
// get file as an imageicon
setIconImage(ic.getImage()); // tell the frame to set
is as its icon
}
Choosing a Layout Manager
LayoutManagers
provide the intelligence to arrange and size components in a container.
To change the layout manager used by your JFrame, Open the JFrame item
on
the Componet Inspector Window (to the right of the display area), then
right click on the layout and select "set layout".
There are several different predefined LayoutManagers available for
you to use:
- FlowLayout
: This is the default (and ugliest) of the layout managers. This layout
manager simply adds components from left to right as long as there is
room.
As soon as the edge of the window is reached it starts a second line.
- GridLayout
: This layout manager is a bit more orderly. When you create it you
specify the number of rows and columns in the grid, then it will put a
component into
each cell. The cells are all the same size. This is great
for
keypads and toolbars, but not so good for generic forms. Components
added to a cell are automatically resized to fit in that cell.
- BorderLayout
: This layout manager divides the panel into 5 areas, a North
area that extends the entire width across the panel, a South area that
extends the entire width across the bottom of the panel, and West,
Center, and East areas that are arranged side by side in between.
Cells in this layout manager are of different sizes and size themselves
automatically. Any cell that does not have a component in it is not
allocated any space on the panel. BorderLayouts are a good way to
organize the content area of a Frame. For example: the North area can
be used for a toolbar, the South area for a status line, the East for a
vertical toolbar, and the center for the working area of the screen.
Note, north, south, east, and west are made as small as possible (give
what's in them), the center then takes up the rest of the space
- GridBagLayout
: This layout manager provides you with the greatest amount of
control over the layout of the panel. Like the GridLayout manager,
GridBagLayout places
component in cells. Unlike GridLayout, a component can occupy (span)
more
than one cell and cells are not all the same size. GridBagLayouts
are
the best way to arrange the fields on a form. This is also the most
complex layout manager to use correctly.
- BoxLayout
: Arranges components in a single row or single column
- Absolute layout : this is a special layout provided by NetBeans
(not in the standard set), that allows you to place and size controls
where you want them. A better alternative is to use the Null layout
which does the same thing and is more transportable
Default Layout Managers (Netbeans forces a FreeDesign if you use the
GUI designer)
- JApplet - BorderLayout (on its content pane)
- JBox - BoxLayout
- JDialog - BorderLayout (on its content pane)
- JFrame - BorderLayout (on its content pane)
- JPanel - FlowLayout
- JWindow - BorderLayout (on its content pane)
Hints on using the NetBeans Form Editor
- If you are using a border, flow, or grid layout you can
drag
and place items directly in the workarea, but it is tricky to do. Its
better to use the component inspector, right click on the frame or
panel you wish to add items to then select "add from palette". The only
time I'd suggest clicking and placing items directly on the display
area
is when you use the Null layout or Free Design Layout.
- To add code to respond to a button, just double click on the
button on the screen area or on the component inspector. NetBeans will
create a method
that is called whenever the button (or menu item) is clicked.
- You can force a field to be a certain size by selecting the
control then opening the "other properties" tab, look for preferred
size.
- You can change the names of controls by right clicking on them
and select rename
- You can change the contents, tool tip text, font, and color via
the properties tab.
JFrame
- Used as the basis to create a program.
- Has BorderLayout
as its default layout manager.
- Border layout gives you 5 regions labeled: north (top),
south(bottom), west (left), east(right), and center. Only one item can
be placed in each region. However, you can place a JPanel in a region,
then place many items in the JPanel. BorderLayout automatically
sizes the north, south, east, west as small as possible (based on whats
in the region), allowing the remaining space for the center region.
- To create a JFrame application,
- Select your directory, right click, select new-gui forms-jframe
- Specify the application name and press finish.
- This creates a new object based on JFrame, complete with a main
method
- The form's editor is then displayed. It consists of the
component inspector window on the right and the work area on the left.
- The form editor will create and edit two files for you.
- .java file has the code
- .form file has information the form editor needs to
run.
- (.class files are the result of compiling.)
- If you copy your work from one place
to another, you need to copy all the files!
- The component inspector lists all GUI objects used in a
hierarchy with JFrame being the owner of everything.
- objects in the component inspector can be selected
by left clicking on them
- right clicking on a component will bring up a menu of
actions that can be performed on the component
- By right clicking on a component in the component inspector you
can add components (add from palette), change the order of components
in panels (change order), and cut/paste components between panels, and
change the properties of the components.
- Since this object inherits JFrame, you can use any of the JFrame
methods.
- Generally, you will not need to modify the main method.
Initialization code can be placed in the constructor.
- In most cases you will need to add the following lines after the
call to initComponents() in the constructor method:
initComponents();
setTitle("My Application"); // set application title
setSize(800,600); // set JFrame size, width, height
in pixels
- It is generally best to only add JPanels to a JFrame, then add
other components to the JPanels.
- To add a JPanel, select the JFrame in the component inspector,
right click on it, select add-from-palette-swing-JPanel.
- A JPanel will be added below (and indented) the JFrame in the
component inspector.
- Select the JPanel by clicking on it, then click on the layout tab
at the bottom of the component inspector and select the region you want
to place the JPanel.
- Right click on the JPanel and give it an appropriate name (e.g.
northPanel).
- Repeat this for the other panels you will need.
- Save your work often as you do the design!
JPanel
- JPanels are used to hold components on the screen, giving
them a "logical grouping".
- JPanels have the
FlowLayout as their default layout manager. But you can change to a
GridLayout, Null layout or a BorderLayout if you need to.
- as a general rule,
- use a flowlayout whenever all the components are to go on one
row,
- use a GridLayout when you have something like a phone or
calaculator keypad where all items are arranged in rows and columns and
are of the same size.
- use a Null layout if you need to create a complex form with
text entry, labels, checkboxes etc. Null layout gives more
control over exact size
and placement of items.
- To change the layout manager for a JPanel, right click on the
JPanel object, then select set layout.
- FlowLayout manager arranges the components from left to
right across the panel, starting a new row when necessary.
- If you use the FlowLayout then you will want to do the following:
- Select the JPanel and open the magnifying glass
- You should see Flowlayout below it. Select the flowlayout.
- You can now set the properties of the Flowlayout.
- Alignment tells flowlayout to center/left/right align
the objects in the panel
- Horizontal gap - determines the amount of space to the
left/right
between objects
- Vertical gap - determines the amount of space between
rows of objects
- If you use the GridLayout then you will want to do the
following:
- Select the JPanel and open the magnifying glass
- You should see GridLayout below it. Select the GridLayout.
- You can now set the properties of the GridLayout.
- Columns tells gridlayout how many columns you
want
- Rows telss the gridlayout how many rows you want
- Horizontal gap - determines the amount of space to the
left/right
between objects
- Vertical gap - determines the amount of space between
rows of objects
- You can change the properties of the JPanel by selecting it. The
ones you are most likely to want to change are
- border - click on the (no border), then click on the
button with the three dots. This will bring up the border options.
- background - sets the background color for the panel,
click on the numbers, then click on the buttons with the three dots to
select a color.
- foreground - sets the text/border color for the panel,
click on the numbers, then click on the buttons with the three dots to
select a color.
- IF YOU ARE USING A Null Layout Manager, then you will
want to set the preferred size for the JPanel, to do this,
click on the "other properties" tab and scroll down to preferred size
and enter the width and height you need in pixels. A line of text is
about 20 pixels high.
- Once you have the name of the JPanel set, its properties set, its
layoutmanager
set, and the properties of the layout manager set, then you can add
components
to the panel.
- To add components to a panel use one of two methods:
- For Gridlayout or Flowlayout, use the component inspector.
- Select the JPanel, then right click and select add from
palette-swing.
- Once the compnent is added, then you can right click on it to
rename
it, and click on it to sets its properties.
- To move a component from one JPanel to another, select the
component, then right click and select "Cut", then select the JPanel
that is to receive it, right click, and select paste.
- To reorder items in a JPanel, select the panel, then right
click and select change-order.
- To change the properties of a component, select the component
then set the properites (color, font, tool-tip text).
- To change the properties of several compenents, hold the
control key down and select all the components you want to change, then
change the properties.
- For Null layout, add directly from the tools area directly
above the
workarea.
- First double click on the JPanel in the component inspector.
This will cause the entire work area to be used for desigining this
panel. Later you can double click on the JFrame to once again see all
the JPanels on the JFrame.
- Select the Swing tab, then click on the component you want to
add,
then click in work area where you want the component. You can now size
and
move the component using your mouse.
- Once the compnent is added, then you can right click on it to
rename
it, and click on it to sets its properties.
Containment Hierarchies
- A JFrame has one content pane (a Container object), a Container
object may hold many components, some of which may be other Containers.
Each
Container can have only one layout manager.
- This allows you divide your screen design into different areas,
each area is a separate JPanel (Container) object with its own layout
manager.
- To keep complexity under control, try to use as few
JPanels as possible.
- A containment hierarchy can be drawn up to help in the design
process.
figure 9-14
Question for thought : How could this application be
rewritten
to have the same interface, but make the Keypad reusable?
Answer - Create a separate class named Keypad, it would
inherit JPanel, reside in its own file (Keypad.java), and handle
setting up the buttons on the grid and handling the button events.