Java GUIs and Graphics
Download
Report
Transcript Java GUIs and Graphics
Java GUIs and Graphics
CNS 3250
Outline
Introduction
Events
Components
Layout managers
Drawing
GUIs and graphics in Java
Portable!
Listeners and events
Components
Layout managers
A design consideration
Data components should exist
independently from GUI components
They should have no knowledge of GUI
GUI components call upon data objects for
information
Why is this a good approach to use?
History
AWT / Event Model (JDK 1.1)
Heavyweight components
Use OS “peers”
Event Dispatch Thread
Listeners to handle events
Swing (Java 2)
Lightweight components
Painted via graphics (not OS peers)
Preserves look and feel across platforms
Events
How does your program know if the user
clicks something with the mouse?
Register a listener object. When the user
clicks with the mouse, the system passes
an event object to the listener.
Listeners
Implements one of the listener interfaces:
ActionListener
MouseListener
MouseMotionListener
WindowListener
etc.
Listener interfaces are defined in java.awt.event
ActionListener interface
Used with buttons, menu items, text fields
Only one method, actionPerformed
Takes an ActionEvent object as parameter
ActionEvent has a method that tells the
command that triggered the name of the
event.
For a button, the text of the button will be the
command by default.
import java.awt.event.*;
import javax.swing.*;
Red Alert!
class RedAlert extends JFrame implements ActionListener {
private JButton redAlertButton;
public RedAlert() {
redAlertButton = new JButton("Red Alert");
add(redAlertButton);
redAlertButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Red Alert")) {
System.out.println("Shields up!");
}
}
public static void main(String[] args) {
RedAlert frame = new RedAlert();
frame.setSize(200, 100);
frame.setVisible(true);
}
}
import java.awt.event.*;
import javax.swing.*;
Red Alert!
class RedAlert extends JFrame implements ActionListener {
private JButton redAlertButton;
public RedAlert() {
redAlertButton = new JButton("Red Alert");
add(redAlertButton);
redAlertButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Red Alert")) {
System.out.println("Shields up!");
}
}
public static void main(String[] args) {
RedAlert frame = new RedAlert();
frame.setSize(200, 100);
frame.setVisible(true);
}
}
MouseListener
Includes several
methods:
mouseClicked
mouseEntered
mouseExited
mousePressed
mouseReleased
Each method gets a
MouseEvent object
that tells the
coordinates of the
mouse and other info.
All methods have to be
defined, whether you
use them or not...
MouseAdapter
Defines all required methods for the
MouseListener interface
Methods are empty.
Override the methods you actually want to
use.
Use by making your class extend
MouseAdapter.
Adapters
All methods for the corresponding listener
interface are defined.
Only useful if your class doesn't need to
inherit from any other class.
Commonly used for mouse listeners, mouse
motion listeners, window listeners.
There is no adapter for action listeners.
Why not?
Using listeners and events
Decide what kind of listener you need
This is usually based on the kind of input and
the type of component you will be using
Define a class for that kind of listener
Make a class that implements the interface
or
Make a class that extends an adapter
Register the listener with the component
add____Listener, e.g. addActionListener
import java.awt.event.*;
import javax.swing.*;
Red Alert!
class RedAlert extends JFrame implements ActionListener {
private JButton redAlertButton;
public RedAlert() {
redAlertButton = new JButton("Red Alert");
add(redAlertButton);
redAlertButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Red Alert")) {
System.out.println("Shields up!");
}
}
public static void main(String[] args) {
RedAlert frame = new RedAlert();
frame.setSize(200, 100);
frame.setVisible(true);
}
}
PolyDraw demo
Elf -- Java Ldraw display
Uses OpenGL (JOGL)
POV-Ray -- Ray tracing
Components
Top-level containers
General-purpose containers
Displays
Controls
Text components
http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html
Top-level containers
Every Java GUI program must have a toplevel container.
Frame (AWT--java.awt)
JFrame (Swing--javax.swing)
http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html
General-purpose containers
Panel
(AWT)
JPanel
(Swing)
http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html
JPanel -- very commonly
used
Container for components
Drawing
Displays
JLabel
Can include an image in addition to (or instead of
text)
Can use HTML formatting
Controls
JButton
JComboBox
JList
JMenuItem
What listeners and events?
Controls
JButton
ActionEvent
JComboBox
ActionEvent
PopupMenuEvent
JList
ListSelectionEvent
JMenuItem
ActionEvent
What listeners and events?
Text components
http://java.sun.com/docs/books/tutorial/uiswing/components/text.html
JTextArea
Used for multi-line text display and editing
Does not handle scrolling internally (as
TextArea does)
Add to JScrollPane to get scrolling
Implements Scrollable interface
Can specify whether or not editing is
allowed
Can specify line wrapping or not
JEditorPane
Can display HTML
Not a "speed demon" according to our text
book
Can get very complicated
'<html><body bgcolor="GRAY">
<center>
<img src="$BASE$MapPics/castle1.png">
<h3>Castle</h3>
</center>
A castle stands on a hill here.
It doesn\'t appear to be inhabited, but it\'s hard to say for sure.
<br></body></html>'
PolyDraw components
JFrame
JButton
JMenuBar
JMenu
JMenuItem
JLabel
JPanel
JTextField
JPanel
JScrollPane
JComboBox
Layout managers
Where should components go?
Usually: x, y coordinates.
In Java location, size, and shape of
components depends on another question:
How big will the user's display be?
Could be anything from a huge, high-res
display to a cell phone
Can change
Good news, bad news
Good news
Adjusts components to fit size/shape of
container
Can write Java GUIs with no special tools
Works well for different fonts, languages
Bad news
Can be difficult to get what you want
Unexpected results
Types of layout managers
BorderLayout
BoxLayout
CardLayout
FlowLayout
GridBagLayout
GridLayout
SpringLayout
Pictures on the following
slides are from the Java
Tutorial:
http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html
Using a layout manager
Create (or get access to) container
Set layout manager for container
Create component
Add component to container
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
JButton button = new JButton("Button 1");
cp.add(button, BorderLayout.CENTER);
These steps vary somewhat depending on the layout manager.
BorderLayout
Very commonly used
The center area grows/shrinks the most
Regions are (or used to be):
Center, North, South, East, West
BoxLayout
Relatively new
Fillers:
strut--1D fixed amount of space
rigid area--2D fixed amount of space
glue--variable amount of space, separates
components as much as possible
(Textbook says "spring" would be a better term
than "glue".)
CardLayout
Used to switch back and forth between
different layouts in the same space
Usually need to keep a reference to the
layout manager object so that you can
control which card is showing.
FlowLayout
The simplest layout manager
Can specify horizontal alignment
GridBagLayout
Very flexible, but very complicated
See the p. 433 in Core Java Vol. I for a
"Recipe for Making a Grid Bag Layout"
Note Step 7: "compile, run, and enjoy"
Must create GridBagConstraints objects
Book recommends a helper class GBC
NetBeans and other IDEs offer visual tools
GridLayout
Useful for a number of components that are
the same size
Position is determined by order that
components are added to the container
SpringLayout
Meant to be as flexible as GridBagLayout
but "more intuitive"
It might be as flexible, but I think it's safe to
say that it isn't more intuitive.