GUI Programming with threads - Andrew.cmu.edu

Download Report

Transcript GUI Programming with threads - Andrew.cmu.edu

GUI Programming with threads
Java GUI programming and Java Threads
GUI example taken from “Computing Concepts with Java 2” by
Cay Horstmann
Thread examples taken from “The Java Programming Language”
By Arnold and Gosling and from Cay Horstmann’s “Core Java 2
Advanced”
Carnegie Mellon University, MISM
1
Frame Windows
A Frame window has a border and a title bar
A Frame window has an addWindowListener method. We can
use this method to add listeners to our frame window.
Carnegie Mellon University, MISM
2
An example
javax means Java standard
extension
import javax.swing.*;
import java.awt.event.*;
public class InternetFrameExample {
public static void main(String[] args) {
JFrame f = new InternetFrame("Example");
f.setTitle("Internet browser");
f.show();
}
}
Tell the window manager to
display the frame.
Carnegie Mellon University, MISM
3
class InternetFrame extends JFrame {
Add the handler
public InternetFrame(String s){
setSize(300,300);
windowOpened()
widowClosed()
}
windowClosing()
:
private class WindowCloser extends WindowAdapter {
:
WindowCloser listener = new WindowCloser();
addWindowListener(listener);
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
Carnegie Mellon University, MISM
4
Carnegie Mellon University, MISM
5
Adding User Interface
Components to a Frame
•Do not draw directly on the surface of a frame.
•Frames have been designed to arrange user interface components.
•User interface components are such things as buttons, menus,
scroll bars, and so on.
•If you want to draw on a frame, draw on a separate component and
then add that component to the frame. The Swing UI toolkit
provides the Jpanel class for this purpose.
Carnegie Mellon University, MISM
6
Drawing on a JPanel
To draw on a Jpanel you override the paintComponent method.
Make sure that from within your paintComponent method you
call super.paintComponent(…) so that the superclass method
paintComponent has a chance to erase the existing contents,
redraw the borders and decorations, etc.
Carnegie Mellon University, MISM
7
Adding the Panel to the JFrame
• The surface of a Swing frame is covered with four
panes.
• Each of these four has a purpose.
• We are interested in getting access to the
JFrame’s content pane.
• So, call the getContentPane on the JFrame.
• This call returns a Container object.
• Add your Panel object to the content pane
Container.
Carnegie Mellon University, MISM
8
Adding a Panel to a JFrame
JFrame
getContentPane()
x = getContentPane (a
contentPane holds
components for display).
x refers to a Container (may
contain other components)
c = a Panel or some other
component.
Add c to x using x’s layout
manager (a content pane uses
Carnegie Mellon University, MISM
9
border layout)
Adding a JTextfield to the
JFrame
JFrame
getContentPane()
cp
class MyFrame extends JFRAME {
private JTextField textField;
public MyFrame() {
Container cp = getContentPane();
textField = new JTextField();
cp.add(textField, “South”);
Carnegie Mellon University, MISM
10
We may want to add a listener to
the TextField
JFrame
getContentPane()
cp
Class MyFrame extends JFRAME {
private JTextField textField;
public myFrame() {
Container cp = getContentPane();
textField = new JTextField();
cp.add(textField, “South”);
textField.addActionListener(
new TextFieldListener());
Carnegie Mellon University, MISM
11
Output first! -- user enters number of eggs and we draw them
Carnegie Mellon University, MISM
12
Strategy
Think about
• What do we want on the screen?
• What events should we listen for?
• What should we do when those events occur?
• What processing will we do when user input arrives?
• What object has responsibilities for what activities?
Think about
• The ‘has-a’ relationship,e.g., the Jframe’s ContentPane “has-a”
Panel and a TextField.
• The ‘is-a’ relationship,e.g., The TextFieldListener ‘is-an’
13
actionListener. Carnegie Mellon University, MISM
// Example
// Eggs.java
We need classes from
the awt, util, and swing
packages.
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
Carnegie Mellon University, MISM
14
public class Eggs
{ public static void main(String[] args)
{ EggFrame frame = new EggFrame();
frame.setTitle("Enter number of eggs");
frame.show();
}
}
This thread is done
after creating a frame and
starting up the frame thread.
A frame now exists and is running.
Carnegie Mellon University, MISM
15
The EggFrame Constructor
• Set the size of the frame
• Add a listener to listen for the stop event
• Create a JPanel object to draw on and a
JTextField object to interact with the user
via the keyboard
• Add a listener for the JTextField
• Add the Jpanel and the JTextField to the
contentPane container.
Carnegie Mellon University, MISM
16
class EggFrame extends JFrame
{
private JTextField textField;
private EggPanel panel;
A listener for the jframe
window
public EggFrame()
{
final int DEFAULT_FRAME_WIDTH = 300;
final int DEFAULT_FRAME_HEIGHT = 300;
setSize(DEFAULT_FRAME_WIDTH,
DEFAULT_FRAME_HEIGHT);
A textField listener
addWindowListener(new WindowCloser());
panel = new EggPanel();
textField = new JTextField();
textField.addActionListener(new TextFieldListener());
Container contentPane = getContentPane();
contentPane.add(panel, "Center");
As before
contentPane.add(textField,
"South");
Carnegie Mellon University, MISM
}
17
Event driven programming
The constructor will be called from our main thread.
The other thread operates asynchronously.
What do we mean by asynchronous execution?
Who is running the show?
Don’t programs run sequentially?
We have to think differently.
Carnegie Mellon University, MISM
18
The TextField
The TextField object will call us when it detects
an event.
We don’t ‘read the input’. We set up a babysitter to
respond.
The TextField object sends us an event object.
Carnegie Mellon University, MISM
19
// Use an inner class to listen on the text field
private class TextFieldListener implements ActionListener {
public void actionPerformed(ActionEvent event)
{
String input = textField.getText();
panel.setEggCount(Integer.parseInt(input));
textField.setText("");
}
}
We do two things when we
have a textfield event.
1) Get the data
2) Tell the panel the number
of eggs to display
Carnegie Mellon University, MISM
20
// Use an inner class to listen on the text field
private class TextFieldListener implements ActionListener {
public void actionPerformed(ActionEvent event)
{
String input = textField.getText();
panel.setEggCount(Integer.parseInt(input));
textField.setText("");
}
}
Note how handy the inner class is. Both panel and
textField are available. What if the listener were not
an object of an inner class. how would it get access
to these variables? We can’t just pass the variables on
the call because
we don’t make the call.
Carnegie Mellon University, MISM
21
private class WindowCloser extends WindowAdapter
{ public void windowClosing(WindowEvent event)
{ System.exit(0);
}
}
}
This is how we respond when the
close signal is received.
system.exit(0) stops the java
virtual machine. 0 means
normal termination.
Carnegie Mellon University, MISM
22
How about the panel object
What are the panel object’s responsibilities?
get input? _____
repaint itself? _____
keep track of the egg count? _____
hold the data it needs to repaint itself? _____
Do we want our panel to inherit properties and methods from any
existing classes? _____
Carnegie Mellon University, MISM
23
How about the panel object
What are the panel object’s responsibilities?
get input? No, that’s the TextField’s job.
repaint itself? Sure, that’s its main job.
keep track of the egg count? Yes, better here where it’s
needed
hold the data it needs to repaint itself? Yes
Do we want our panel to inherit properties from any existing
classes? Sure, we want to re-use existing code whenever possible.
Carnegie Mellon University, MISM
24
How about the panel object
When should the panel object repaint itself?
What will the panel need to repaint itself?
Who actually calls the paintComponent method?
Carnegie Mellon University, MISM
25
How about the panel object
When should the panel object repaint itself?
When a new input arrives from the user.
When the egg count changes.
What will the panel need to repaint itself?
A graphics object to draw on.
Who actually calls the paintComponent method?
While we have to provide a paintComponent method
we don’t call it directly.
It’s called by the Java run-time environment after
we make a call on
repaint.
Carnegie
Mellon University, MISM
26
class EggPanel extends JPanel
{
public void paintComponent(Graphics g)
{ super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
// draw eggCount ellipses with random centers
Random generator = new Random();
for (int i = 0; i < eggCount; i++)
{ double x = getWidth() * generator.nextDouble();
double y = getHeight() * generator.nextDouble();
Ellipse2D.Double egg = new Ellipse2D.Double(x, y,
EGG_WIDTH, EGG_HEIGHT);
g2.draw(egg);
}
Carnegie Mellon University, MISM
}
27
public void setEggCount(int count)
{ eggCount = count;
repaint();
}
private int eggCount;
private static final double EGG_WIDTH = 30;
private static final double EGG_HEIGHT = 50;
}
Carnegie Mellon University, MISM
28