View
247
Download
0
Tags:
Embed Size (px)
Citation preview
Carnegie Mellon University, MISM 1
Java GUI programming and Java Threads
GUI example taken from “Computing Concepts with Java 2” byCay Horstmann
Thread examples taken from “The Java Programming Language”By Arnold and Gosling and from Cay Horstmann’s “Core Java 2 Advanced”
GUI Programming with threads
Carnegie Mellon University, MISM 2
Frame Windows
A Frame window has a border and a title bar
A Frame window has an addWindowListener method. We canuse this method to add listeners to our frame window.
Carnegie Mellon University, MISM 3
An example
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(); }}
javax means Java standardextension
Tell the window manager todisplay the frame.
Carnegie Mellon University, MISM 4
class InternetFrame extends JFrame {
public InternetFrame(String s){
setSize(300,300); WindowCloser listener = new WindowCloser(); addWindowListener(listener); }
private class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) { System.exit(0); } } }
windowOpened()widowClosed()windowClosing() : :
Add the handler
Carnegie Mellon University, MISM 6
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 7
Drawing on a JPanel
To draw on a Jpanel you override the paintComponent method.
Make sure that from within your paintComponent method youcall 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 8
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 9
Adding a Panel to a JFrame
x = getContentPane (a contentPane holdscomponents 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 layoutmanager (a content pane usesborder layout)
JFrame
getContentPane()
Carnegie Mellon University, MISM 10
Adding a JTextfield to the JFrame
JFrame
getContentPane()
class MyFrame extends JFRAME { private JTextField textField; public MyFrame() { Container cp = getContentPane();
textField = new JTextField();
cp.add(textField, “South”);
cp
Carnegie Mellon University, MISM 11
We may want to add a listener to the TextField
JFrame
getContentPane()
Class MyFrame extends JFRAME { private JTextField textField; public myFrame() { Container cp = getContentPane();
textField = new JTextField();
cp.add(textField, “South”);
textField.addActionListener( new TextFieldListener());
cp
Carnegie Mellon University, MISM 13
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’ actionListener.
Carnegie Mellon University, MISM 14
// Example// Eggs.java
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;
We need classes fromthe awt, util, and swingpackages.
Carnegie Mellon University, MISM 15
public class Eggs{ public static void main(String[] args) { EggFrame frame = new EggFrame(); frame.setTitle("Enter number of eggs"); frame.show(); }}
This thread is doneafter creating a frame andstarting up the frame thread.
A frame now exists and is running.
Carnegie Mellon University, MISM 16
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 17
class EggFrame extends JFrame{ private JTextField textField; private EggPanel panel;
public EggFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
addWindowListener(new WindowCloser()); panel = new EggPanel(); textField = new JTextField(); textField.addActionListener(new TextFieldListener()); Container contentPane = getContentPane(); contentPane.add(panel, "Center"); contentPane.add(textField, "South"); }
A listener for the jframewindow
A textField listener
As before
Carnegie Mellon University, MISM 18
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.
Event driven programming
Carnegie Mellon University, MISM 19
The TextField
The TextField object will call us when it detectsan event.
We don’t ‘read the input’. We set up a babysitter torespond.
The TextField object sends us an event object.
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(""); } } We do two things when we
have a textfield event.1) Get the data2) Tell the panel the number of eggs to display
Carnegie Mellon University, MISM 21
// 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 notan object of an inner class. how would it get accessto these variables? We can’t just pass the variables onthe call because we don’t make the call.
Carnegie Mellon University, MISM 22
private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } }}
This is how we respond when theclose signal is received.system.exit(0) stops the java virtual machine. 0 means normal termination.
Carnegie Mellon University, MISM 23
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 anyexisting classes? _____
Carnegie Mellon University, MISM 24
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 25
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 26
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 27
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); } }