Java GUIs and Graphics - Utah Valley University

Download Report

Transcript Java GUIs and Graphics - Utah Valley University

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.
Drawing
 Core Java (8th ed.) Vol. I, Ch. 7
 Especially pages 296-322
 Core Java (8th ed.) Vol. II, Ch. 7
Graphics class
 Override paintComponent, which takes an
object of class Graphics as a parameter
 Call methods of Graphics class to draw
shapes:
public void paintComponent (Graphics g)
{
g.setColor(Color.blue);
g.fillOval(10, 20, 30, 30);
}
Upper left
“corner”
Width and
height
Graphics
import java.awt.*;
import javax.swing.*;
Jframe, JPanel
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
g.fillOval(10, 20, 30, 30);
}
public static void main(String args[]) {
JFrame frame = new JFrame();
Draw draw = new Draw();
frame.add(draw);
frame.setSize(200, 150);
frame.setVisible(true);
}
}
import java.awt.*;
import javax.swing.*;
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
g.fillOval(10, 20, 30, 30);
}
paintComponent is not explicitly called.
public static void main(String args[]) {
JFrame frame = new JFrame();
Draw draw = new Draw();
frame.add(draw);
frame.setSize(200, 150);
frame.setVisible(true);
}
}
paintComponent
 Takes one parameter of type Graphics
and has no return value
 Must be ready to execute at any time
 Don’t know when or how many times the JVM
will call it.
 Don’t call directly--call repaint method of
component to tell the JVM to call
paintComponent
JPanel
 Opaque--must paint all pixels within its
bounds
 Call parent paintComponent to paint
background:
public void paintComponent (Graphics g)
{
super.paintComponent(g);
// drawing code goes here
}
Drawing bitmaps
 drawImage method of Graphics
 Coordinates of upper left corner
 Optionally height and width
 Last parm is ImageObserver
Example on next
slide.
public class Bitmap extends JPanel {
Image img = null;
Why check this?
public void paintComponent(Graphics g) {
if (img != null) {
g.drawImage(img, 10, 10, 180, 120, this);
}
Upper left
Width and
}
ImageObserver
“corner”
height
public static void main(String args[]) {
Bitmap draw = new Bitmap();
try {
In javax.imageio
draw.img =
ImageIO.read(new File("dunluce.jpg"));
} catch (IOException x) {
x.printStackTrace();
}
draw.repaint();
}
}
Some lines of code
have been removed.
Graphics2D
 More shapes
 Control over stroke--lines more than one
pixel wide
 More fill options
 Transformation--translate, rotate, scale
 Clip shapes and select composition rules
 Give rendering hints
Core Java, p. 522 (8th ed.)
Using Java 2D Graphics API
 Cast Graphics parameter to Graphics2D
 Set stroke, paint, transformations, etc.
 Create a shape
 See shape hierarchy on page 526 (8th ed.)
 Call draw or fill methods of
Graphics2D object