Week 8: Java GUI Part I
Overview
- Java gives you a class library for basic GUI programming
called the Abstract Window Toolkit (AWT)
- Platform independent
- Common denominator approach ... not looking good
- Write once, debug everywhere
- Naturally, programmer has to write a lot of code
Frames and Windows
import java.awt.*;
import java.awt.event.*;
public class CloseableFrame extends Frame
{ public CloseableFrame()
{ addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) { System.exit(0); } } );
setSize(300, 200);
setTitle(getClass().getName());
}
}
- Use CloseableFrame as follows:
import java.awt.*;
public FirstFrame extends CloseableFrame
{
public static void main(String [] args)
{
FirstFrame f = new FirstFrame();
f.show();
}
}
- Java will build the data structure that contains all the
necessary information so that the underlying windowing
system can display a window
- Inheritance hierarchy for the Frame class
Object <- Component <- Container <- Window <-
Frame
- Frame has methods setTitle to change the title
bar and setResizable to determine if a frame is
resizeable by the user or not
- The show method is actually under Window class
- The setlocation method is in Component class that lets
you reposition a component:
setLocation(int x, int y)
- Note that for a frame, the coordinates are taken relative
to the whole screen (thus, we need native information to
find out screen information
- In Java, system-dependent information can be obtained
under toolkit.
Example:
// Create a Frame in the center
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenHeight = d.height;
int screenWidth = d.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
Display Information in a Window
- You can put text messages or graphics into a window, by
overriding the paint method
- The paint method will take a Graphics object
- A Graphics object "contains" a collection of
settings for drawing images and text. All drawing in Java
must go through a Graphic object
Example:
import java.awt.*;
public class myAWT extends CloseableFrame
{
public void paint(Graphic g)
{
g.drawString("This is a line of text", 75, 100);
}
public static void main(String[] args)
{
Frame f = new myAWT();
f.show();
}
}
Text and Fonts
- Only SanSerif, Serif, Monospaced, Dialog, DialogInput
exist in all client machine. (They usually get mapped to
other fonts, e.g. SansSerif to Arial.)
- Use the Font class to change the font !
Example:
public void paint(Graphic g)
{
Font f = new Font("ScansSerif", Font.BOLD, 14);
g.setFont(f);
g.drawString("This is a line of text", 75, 100);
}
- It is not easy to find out additional fonts on a specific
system. Only getFontList method in Toolkit
class is available. It returns an array of strings with
the font names that are known to be available.
- User installed fonts are not reported.
Colors
- The setColor method call selects a color that is used for
all drawing operations on the graphics context or
component
- Color(byte redness, byte greeness, byte blueness)
- Standard Colors available are: black, blue, cyan,
darkGray, gray, green, lightGray, magenta, orange, pink,
red, white, yellow
Example:
f.setColor(Color.pink);
f.drawString("Hello", 75, 100);
f.setColor(new Color(0, 128, 128)); // some kind of blue and green
f.drawString("www.openloop.com", 75, 125);
f.setBackground(SystemColor.window); // set bg color of frame to default color used by all windows on desktop
Drawing
- Use drawLine, drawArc, drawPolyLine, and drawPolygon
methods in java.awt.Graphics to draw straight and curved
lines on a graphics object.
- Basically:
- Create a polygon object
- add points to the object
- use the drawPolygon(Polygon p) method described
here to draw the polygon
Example:
// Make sure we start in the left upper corner without the window system overhead
g.translate(getInsets().left, getInsets().top);
int r = 40; // radius of circle bounding PacMan(R)
int cx = 50; // center of that circle
int cy = 100;
int angle = 30; // opening angle of mouth
int dx = (int)(r * Math.cos(angle * Math.PI / 180));
int dy = (int)(r * Math.sin(angle * Math.PI / 180));
// Draw the "PackMan" shape
g.drawLine(cx, cy, cx + dx, cy + dy); // lower jaw
g.drawLine(cx, cy, cx + dx, cy - dy); // upper jaw
g.drawArc(cx - r, cy - r, 2 * r, 2 * r, angle,
360 - 2 * angle);
// Draw a "Five angles" shape
Polygon p = new Polygon();
cx = 150;
int i;
for (i = 0; i < 5; i++)
p.addPoint(
(int)(cx + r * Math.cos(i * 2 * Math.PI / 5)),
(int)(cy + r * Math.sin(i * 2 * Math.PI / 5)));
g.drawPolygon(p);
- Use fillRec, fillRoundRect, fill3DRect, fillOval,
fillArc, fillPolygon to draw filling shape
Example:
g.fillRect(0, 0, 80, 30); // x,y,width,height
g.fillOval(0, 100, 80, 30); // x,y,width,height
Images
- For import images, use the Toolkit object. It will only
read GIF and JPEG files
Example:
// Get from local file system
String filename = "ball.gif";
Image myimage = Toolkit.getDefaultToolkit().getImage(filename);
// Get from the internet
URL myurl = new URL("http://www.openloop.com/myimage.gif");
Image myimage = Toolkit.getDefaultToolkit().getImage(myurl);
// ...
// Draw out the image
public void paint(Graphics g)
{
g.drawImage(myimage, 0, 0, this);
}
User Interface Components - Layout Manager
- Java provide standard UI components and Layout manager
- Native friendly: A button on Motif looks just like a
Motif button. A MS windows button just like a MS windows
button
- Without using standard Java UI components, we can have lightweight
component - swing, JFC. Then, applications can have
a uniform look and feel across platforms
- There are five basic layout managers:
- Flow Layout will automatically arrange
the UI component, we can set the alignment:
- setLayout(new FlowLayout(FlowLayout.LEFT);
- Border Layout has the five areas called
North, South, {East, West, and Center}
North
West - Center - East
South
(Note: The default layout manager for Frame Border
Layout)
- When the container is resized, the thickness of the
borders is unchanged, but the center area changes its
size
setLayout(new BorderLayout());
add(new Button, "East");
- Card Layout: Kind of like a tabbed
dialog
- Grid Layout defines everything in a x-y
coordinate system
- Example:
panel.setLayout(new GridLayout(5, 4));
// Add the components, starting with the first entry in the first row, then
// second entry in the first row, and so on.
panel.add(new Button("1");
panel.add(new Button("2");
- Grid Bag Layout - This mother of all
layout managers. Everything is in a piece of graph paper,
and we will use that for our lab.
Java UI Components
Button
// Create a button
Button myButton = new Button("OK");
// Set the layout manager
// FlowLayout will automatically arrange the item
setLayout(new FlowLayout());
// Add the button
add(myButton);
// Add the event handler, next week
myButton.addActionListener(this);
Panel
- We use panel to act as a container to hold other Java UI
Component
- The default layout manager for a panel is a FlowLayout
Example:
public FirstPanel()
{
Panel p = new Panel();
p.add(button1);
p.add(button2);
add(p, "South");
}
Canvases
- Usually, we do not just draw on the Windows, since the
drawing might overlap other components.
- We use canvases instead (1. Derive a new class from
Canvas, 2. Override the paint method for drawing)
- Example:
class myCan extends Canvas
{
public void paint (Graphics g)
{
g.drawOval(0, 0, 50, 50);
...
}
...
}
...
// In other file
...
hi = new myCan();
add(hi, "Center");
...
Text field
- Good for single line of input
- Always returns a String object
- Example:
// Declare the new TextField
TextField age = new TextField("25", 20);
// Set the value
age.setText("30");
...
// Get the value
String internalAgeV = age.getText().trim();
// Change to integer value
int agei = Integer.parseInt(age.getText().trim());
Text Areas
Labels
- UI component that holds one line of plain text
- To label a component that does not itself come with an
identifier
- Construct a Label component with the correct text
- Place it close to the other component (e.g. TextField)
- Example:
p.add(new Label("Options");
Check Box
- The name of the class is Checkbox
- Go for collecting yes or no
- Can have multiple checkboxes and check them all
- Example:
// Create one checkbox
Checkbox c = new Checkbox(name);
c.addItemListener(this);
p.add(c);
Check Box Groups
- Only one box can be checked in a group
- When another box is checked, the previous box is
automatically unchecked
- Radio button group
- Example:
CheckboxGroup g = new CheckboxGroup();
// The checkbox is not checked at first
small = new Checkbox("Small", g, false);
large = new Checkbox("Large", g, true);
- We only add the Checkbox, not the CheckboxGroup into the
panel (Lab will cover this as well)
- Choice Boxes (Drop-Down Lists)
- The pull down list
- Can only take one of the selection
- When user clicks on the field, a list of choices drops
down, and the user can then select one of them
- Example:
// Create the Choice box and add two items within that
style = new Choice();
style.add("Option 1");
style.add("Option 2");
// insert or remove element
style.insert("Option X", 0); // Add at the
beginning
...
// Remove stuffs
style.remove("Option 2");
style.remove(0); // Remove whatever in index 0
List
- Allow the user to make multiple selections
- Example:
states = new List(4, true); // List of 4 items, allow mult
selection
states.add("State 1");
states.add("State 2");
...
// Add and select some items
states.add("State X");
states.select(0); // select index 0
states.select(1); // select index 1
Lab
Create a Java application Week 8 that
has the look and feel of the following:

Note:
- You can use whatever layout manager as you like, there
are more then one way to construct a GUI interface
- The above example uses GridBagLayout as the main layout
manager
- FlowLayout for buttons
- CheckboxGroup for Options
- List for web sites
- Labels with setFont for Text
- CloseableFrame is also
used as the base (just import this 7 lines class for now,
we will take about event handler next week)
Copyright
1996-2001 OpenLoop Computing. All rights reserved.