AWT Components: Simple User Interfaces: For Live Java-Related Training
AWT Components: Simple User Interfaces: For Live Java-Related Training
AWT Components:
Simple User Interfaces
Originals of slides and source code for examples: http://courses.coreservlets.com/Course-Materials/java.html
Also see the Java 8 tutorial – http://www.coreservlets.com/java-8-tutorial/
and customized Java training courses (onsite or at public venues) – http://courses.coreservlets.com/java-training.html
GUI Libraries
in Java SE
Background
10
© 2014 Marty Hall
Foundational AWT
Window Types
Summary
• Canvas
– Purpose:
• Reusable picture or drawing area. Basis for custom component.
– Code
• Allocate Canvas, give it a size, add it to existing window.
• Panel
– Purpose
• To group other components into rectangular regions.
– Code
• Allocate Panel, put other components in it, add to window.
• Frame
– Purpose
• Core popup window. Main window for your application.
– Code
• Allocate Frame, give it a size, add stuff to it, pop it up.
12
Canvas
• Major purposes
– A drawing area
– A custom component that does not need to contain any
other component (e.g., an image button)
• Default layout manager: none
– Canvas is not a Container, so cannot enclose components
• Creating and using
– Allocate it Since Canvas is often the starting point for a component that has
a custom paint method or event handlers, you often do
• Canvas c = new Canvas(); MySpecializedCanvas c = new MySpecializedCanvas(…).
– Give it a size
• c.setSize(width, height);
– Drop it in existing window
If this code is in the main window, then “someWindow” is “this” and can be omitted.
13
• someWindow.add(c); I.e, the init method of an applet would add a Canvas to itself just with “add(c);”.
Canvas Example
import java.awt.*;
15
16
Lightweight Components
• Idea
– Regular AWT windows are native windows behind the
scenes. So, they are rectangular and opaque.
– You can make “lightweight components” – components
that are really pictures, not windows, behind the scenes.
• These don’t have the rectangular/opaque restrictions, but
building them is usually more trouble than it is worth in the
AWT library. The Swing library makes it simple with a
“setOpaque” method.
• Code
– If you really want to do it yourself in AWT, you have to
tell Java how to calculate the minimum and preferred
sizes (see later section on layout managers).
• Even so, it can have tricky interactions if the enclosing
window has a custom paint method. Use Swing instead!
17
Lightweight Components:
Example
public class BetterCircle extends Component {
private Dimension preferredDimension;
private int width, height;
No Panels: Example
import java.applet.Applet;
import java.awt.*;
22
No Panels: Result
23
Panels: Example
import java.applet.Applet;
import java.awt.*;
25
Container Class
• Idea
– Ancestor of all window types except Canvas. So, these methods are
common among almost all windows.
• Useful Container methods
– add
• Add a component to the container (in the last position in the
component array)
• If using BorderLayout, you can also specify in which region to
place the component
– remove
• Remove the component from the window (container)
– getComponents
• Returns an array of components in the window
• Used by layout managers
– setLayout
26 • Changes the layout manager associated with the window
Frame Class
• Major Purpose
– A stand-alone window with its own title and menu bar,
border, cursor, and icon image
• Can contain other GUI components
• Default layout manager: BorderLayout
– BorderLayout
• Divides the screen into 5 regions: North, South, East,
West, and Center
– To switch to the applet’s layout manager use
• setLayout(new FlowLayout());
• Creating and using – two approaches:
– A fixed-size Frame
– A Frame that stretches to fit what it contains
27
28
Creating a Frame that Stretches
to Fit What it Contains
• Approach
Frame frame = new Frame(titleString);
frame.setLocation(left, top);
frame.add(somePanel, BorderLayout.CENTER);
...
frame.pack();
frame.setVisible(true);
• Note
– Again, be sure to pop up the frame after adding the
components
29
Frame Example 1
• Creating the Frame object in main
public class FrameExample1 {
public static void main(String[] args) {
Frame f = new Frame("Frame Example 1");
f.setSize(400, 300);
f.setVisible(true);
}
}
30
Frame Example 2
• Using a Subclass of Frame
A Closeable Frame
• CloseableFrame.java
public class CloseableFrame extends Frame {
public CloseableFrame(String title) {
super(title);
addWindowListener(new ExitListener());
}
}
• ExitListener.java
public class ExitListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
Download these two classes from the source code in the tutorial,
then use CloseableFrame wherever you would have used Frame.
32
Frame Example 3
• Using a Subclass of CloseableFrame
public class FrameExample3 extends CloseableFrame {
public FrameExample3() {
super("Frame Example 3");
setSize(400, 300);
setVisible(true);
}
33
35
39
public ActionExample2() {
super("Handling Events in Other Object");
setLayout(new FlowLayout());
setFont(new Font("Serif", Font.BOLD, 18));
button1 = new Button("Resize to 300x200");
button1.addActionListener(this);
add(button1);
// Add button2 and button3 in the same way…
...
setSize(400, 300);
setVisible(true);
}
40
Centralized Event Processing:
Example (Continued)
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button1) {
updateLayout(300, 200);
} else if (event.getSource() == button2) {
updateLayout(400, 300);
} else if (event.getSource() == button3) {
updateLayout(500, 400);
}
}
Semi-Centralized Event
Processing: Example
import java.awt.*;
import java.awt.event.*;
public ActionExample3() {
super("Handling Events in Other Object");
setLayout(new FlowLayout());
setFont(new Font("Serif", Font.BOLD, 18));
button1 = new Button("Resize to 300x200");
button1.addActionListener(new ResizeHandler(300, 200));
add(button1);
// Add button2 and button3 in the same way…
...
setSize(400, 300);
setVisible(true);
}
42
Semi-Centralized Event
Processing: Example (Cont)
private void updateLayout(int width, int height) {
setSize(width, height);
invalidate();
validate();
}
private class ResizeHandler implements ActionListener {
private int width, height;
public ResizeHandler(int width, int height) {
this.width= width;
this.height = height;
}
public void actionPerformed(ActionEvent event) {
updateLayout(width, height);
}
}
45
Buttons (Continued)
• Event processing methods
– addActionListener/removeActionListener
• Add/remove an ActionListener that processes
ActionEvents in actionPerformed
– processActionEvent
• Low-level event handling
• General methods inherited from component
– getForeground/setForeground
– getBackground/setBackground
– getFont/setFont
46
Button: Example
public class Buttons extends Applet {
private Button button1, button2, button3;
public void init() {
button1 = new Button("Button One");
button2 = new Button("Button Two");
button3 = new Button("Button Three");
add(button1);
add(button2);
add(button3);
}
}
47
49
Checkbox, Example
public class Checkboxes extends CloseableFrame {
public Checkboxes() {
super("Checkboxes");
setFont(new Font("SansSerif", Font.BOLD, 18));
setLayout(new GridLayout(0, 2));
Checkbox box;
for(int i=0; i<12; i++) {
box = new Checkbox("Checkbox " + i);
if (i%2 == 0) {
box.setState(true);
}
add(box);
}
pack();
setVisible(true);
}
}
50
Other Checkbox Methods
• getState/setState
– Retrieves or sets the state of the checkbox: checked (true)
or unchecked (false)
• getLabel/setLabel
– Retrieves or sets the label of the checkbox
– After changing the label invalidate and validate the
window to force a new layout
someCheckbox.setLabel("A New Label");
someCheckbox.getParent().invalidate();
someCheckbox.getParent().validate();
• addItemListener/removeItemListener
– Add or remove an ItemListener to process
ItemEvents in itemStateChanged
• processItemEvent(ItemEvent event)
– Low-level event handling
51
53
CheckboxGroup: Example
import java.applet.Applet;
import java.awt.*;
57
59
61
62
Other GUI Controls
• Choice Lists (Combo Boxes)
• Textfields
63
• Labels
64
Summary
• Native components behind the scenes
– So, all windows and graphical components are rectangular and
opaque, and take look-and-feel of underlying OS.
• Windows
– Canvas: drawing area or custom component
– Panel: grouping other components
– Frame: popup window
• GUI Controls
– Button: handle events with ActionListener
– Checkbox, radio button: handle events with ItemListener
– List box: handle single click with ItemListener,
double click with ActionListener
– To quickly determine the event handlers for a component,
simply look at the online API
• addXxxListener methods are at the top
65
Questions?
More info:
http://courses.coreservlets.com/Course-Materials/java.html – General Java programming tutorial
http://www.coreservlets.com/java-8-tutorial/ – Java 8 tutorial
http://courses.coreservlets.com/java-training.html – Customized Java training courses, at public venues or onsite at your organization
http://coreservlets.com/ – JSF 2, PrimeFaces, Java 7 or 8, Ajax, jQuery, Hadoop, RESTful Web Services, Android, HTML5, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training