/** Try out a few instances of the Counter2 class.
Driver class that creates three threaded objects (Counter2) that count from 0 to 4. In this case,
the driver does not start the threads, as each thread is automatically started in Counter2's
constructor. Uses the following class:
Counter2Test.java
Counter2.java
**************************
public class Counter2Test {
public static void main(String[] args) {
Counter2 c1 = new Counter2(5);
Counter2 c2 = new Counter2(5);
Counter2 c3 = new Counter2(5);
}
}
* Counter2.java A Runnable that counts to a specified value and sleeps a random number of seconds
in between counts. Here, the thread is started automatically when the object is instantiated.
/** A Runnable that counts up to a specified
* limit with random pauses in between each count.
public class Counter2 implements Runnable {
private static int totalNum = 0;
private int currentNum, loopLimit;
public Counter2(int loopLimit) {
this.loopLimit = loopLimit;
currentNum = totalNum++;
Thread t = new Thread(this);
t.start();
}
private void pause(double seconds) {
try { Thread.sleep(Math.round(1000.0*seconds)); }
catch(InterruptedException ie) {}
}
public void run() {
for(int i=0; i
Aug 25
Counter2Test.java Driver class that creates three threaded objects (Counter2) that count from 0 to 4.
Aug 25
Template illustrating the first approach for creating a class with thread behavior.
** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class ThreadClass extends Thread {
public void run() {
// Thread behavior here.
}
}
Aug 25
Creates three radio buttons and illustrates handling
JRadioButtonTest.java Creates three radio buttons and illustrates handling ItemEvents in response to selecting a radio button.
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*/
public class JRadioButtonTest extends JPanel
implements ItemListener {
public JRadioButtonTest() {
String[] labels = {"Java Swing","Java Servlets",
"JavaServer Pages"};
JRadioButton[] buttons = new JRadioButton[3];
ButtonGroup group = new ButtonGroup();
for(int i=0; i
Aug 25
Simple button that the user can select to load the entered URL.
JIconButton.java A simple button that the user can select to load the entered URL.
import javax.swing.*;
/** A regular JButton created with an ImageIcon and with borders
* and content areas turned off.
*
*/
public class JIconButton extends JButton {
public JIconButton(String file) {
super(new ImageIcon(file));
setContentAreaFilled(false);
setBorderPainted(false);
setFocusPainted(false);
}
}
Aug 25
A simple button that contains an image and a label for use in a toolbar
ToolBarButton.java A simple button that contains an image and a label for use in a toolbar.
import java.awt.*;
import javax.swing.*;
/** Part of a small example showing basic use of JToolBar.
* The point here is that dropping a regular JButton in a
* JToolBar (or adding an Action) in JDK 1.2 doesn't give
* you what you want -- namely, a small button just enclosing
* the icon, and with text labels (if any) below the icon,
* not to the right of it. In JDK 1.3, if you add an Action
* to the toolbar, the Action label is no longer displayed.
*
*/
public class ToolBarButton extends JButton {
private static final Insets margins =
new Insets(0, 0, 0, 0);
public ToolBarButton(Icon icon) {
super(icon);
setMargin(margins);
setVerticalTextPosition(BOTTOM);
setHorizontalTextPosition(CENTER);
}
public ToolBarButton(String imageFile) {
this(new ImageIcon(imageFile));
}
public ToolBarButton(String imageFile, String text) {
this(new ImageIcon(imageFile));
setText(text);
}
}
Aug 25
Demonstrates the use of a JColorChooser which presents a dialog with three different tabbed panes to allow the user to select a color preference
Demonstrates the use of a JColorChooser which presents a dialog with three different tabbed panes to allow the user to select a color preference. The dialog returns a Color object based on the user’s selection or null if the user entered Cancel.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/** Simple example illustrating the use of internal frames.
*
* */
public class JInternalFrames extends JFrame {
public static void main(String[] args) {
new JInternalFrames();
}
public JInternalFrames() {
super("Multiple Document Interface");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
JDesktopPane desktop = new JDesktopPane();
desktop.setBackground(Color.white);
content.add(desktop, BorderLayout.CENTER);
setSize(450, 400);
for(int i=0; i<5; i++) {
JInternalFrame frame
= new JInternalFrame(("Internal Frame " + i),
true, true, true, true);
frame.setLocation(i*50+10, i*50+10);
frame.setSize(200, 150);
frame.setBackground(Color.white);
frame.setVisible(true);
desktop.add(frame);
frame.moveToFront();
}
setVisible(true);
}
}
Aug 25
Creates various buttons. In Swing
import java.awt.*;
import javax.swing.*;
/** Simple example illustrating the use of JButton, especially
* the new constructors that permit you to add an image.
*
*/
public class JButtons extends JFrame {
public static void main(String[] args) {
new JButtons();
}
public JButtons() {
super("Using JButton");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton button1 = new JButton("Java");
content.add(button1);
ImageIcon cup = new ImageIcon("images/cup.gif");
JButton button2 = new JButton(cup);
content.add(button2);
JButton button3 = new JButton("Java", cup);
content.add(button3);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition(SwingConstants.LEFT);
content.add(button4);
pack();
setVisible(true);
}
}
Aug 25
Multithreaded Graphics and Double Buffering
ShipSimulation.java Illustrates the basic approach of multithreaded graphics whereas a thread adjusts parameters affecting the appearance of the graphics and then calls repaint to schedule an update of the display.
import java.applet.Applet;
import java.awt.*;
public class ShipSimulation extends Applet implements Runnable {
...
public void run() {
Ship s;
for(int i=0; i
* When the "stop" button is pressed, stop the thread and
* clear the Vector of circles.
*/
public void actionPerformed(ActionEvent event) {
if (event.getSource() == startButton) {
if (circles.size() == 0) {
// Erase any circles from previous run.
getGraphics().clearRect(0, 0, getSize().width,
getSize().height);
animationThread = new Thread(this);
animationThread.start();
}
int radius = 25;
int x = radius + randomInt(width - 2 * radius);
int y = radius + randomInt(height - 2 * radius);
int deltaX = 1 + randomInt(10);
int deltaY = 1 + randomInt(10);
circles.addElement(new MovingCircle(x, y, radius, deltaX,
deltaY));
} else if (event.getSource() == stopButton) {
if (animationThread != null) {
animationThread = null;
circles.removeAllElements();
}
}
repaint();
}
/** Each time around the loop, call paint and then take a
* short pause. The paint method will move the circles and
* draw them.
*/
public void run() {
Thread myThread = Thread.currentThread();
// Really while animationThread not null
while(animationThread==myThread) {
repaint();
pause(100);
}
}
/** Skip the usual screen-clearing step of update so that
* there is no flicker between each drawing step.
*/
public void update(Graphics g) {
paint(g);
}
/** Erase each circle's old position, move it, then draw it
* in new location.
*/
public void paint(Graphics g) {
MovingCircle circle;
for(int i=0; i windowWidth) && (deltaX > 0)) {
setDeltaX(-deltaX);
}
if ((y -radius < 0) && (deltaY < 0)) {
setDeltaY(-deltaY);
} else if((y + radius > windowHeight) && (deltaY > 0)) {
setDeltaY(-deltaY);
}
}
public int getDeltaX() {
return(deltaX);
}
public void setDeltaX(int deltaX) {
this.deltaX = deltaX;
}
public int getDeltaY() {
return(deltaY);
}
public void setDeltaY(int deltaY) {
this.deltaY = deltaY;
}
}
*//
SimpleCircle.java A class to store the x, y, and radius of a circle. Also, provides a draw method to paint the circle on the graphics object.
import java.awt.*;
/** A class to store an x, y, and radius, plus a draw method.
*
*/
public class SimpleCircle {
private int x, y, radius;
public SimpleCircle(int x, int y, int radius) {
setX(x);
setY(y);
setRadius(radius);
}
/** Given a Graphics, draw the SimpleCircle
* centered around its current position.
*/
public void draw(Graphics g) {
g.fillOval(x - radius, y - radius,
radius * 2, radius * 2);
}
public int getX() { return(x); }
public void setX(int x) { this.x = x; }
public int getY() { return(y); }
public void setY(int y) { this.y = y; }
public int getRadius() { return(radius); }
public void setRadius(int radius) {
this.radius = radius;
}
}
*//
DoubleBufferBounce.java An enhancement to the previous applet containing bouncing circles. In this case, double buffering is used to improve the animation; all incremental updating is done in an off-screen image and then the image is drawn to the screen.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
/** Bounce circles around on the screen, using double buffering
* for speed and to avoid problems with overlapping circles.
* Overrides update to avoid flicker problems.
*
*/
public class DoubleBufferBounce extends Applet implements
Runnable, ActionListener {
private Vector circles;
private int width, height;
private Image offScreenImage;
private Graphics offScreenGraphics;
private Button startButton, stopButton;
private Thread animationThread = null;
public void init() {
setBackground(Color.white);
width = getSize().width;
height = getSize().height;
offScreenImage = createImage(width, height);
offScreenGraphics = offScreenImage.getGraphics();
// Automatic in some systems, not in others.
offScreenGraphics.setColor(Color.black);
circles = new Vector();
startButton = new Button("Start a circle");
startButton.addActionListener(this);
add(startButton);
stopButton = new Button("Stop all circles");
stopButton.addActionListener(this);
add(stopButton);
}
/** When the "start" button is pressed, start the animation
* thread if it is not already started. Either way, add a
* circle to the Vector of circles that are being bounced.
*
* When the "stop" button is pressed, stop the thread and
* clear the Vector of circles.
*/
public void actionPerformed(ActionEvent event) {
if (event.getSource() == startButton) {
if (circles.size() == 0) {
animationThread = new Thread(this);
animationThread.start();
}
int radius = 25;
int x = radius + randomInt(width - 2 * radius);
int y = radius + randomInt(height - 2 * radius);
int deltaX = 1 + randomInt(10);
int deltaY = 1 + randomInt(10);
circles.addElement(new MovingCircle(x, y, radius, deltaX,
deltaY));
repaint();
} else if (event.getSource() == stopButton) {
if (animationThread != null) {
animationThread = null;
circles.removeAllElements();
}
}
}
/** Each time around the loop, move each circle based on its
* current position and deltaX/deltaY values. These values
* reverse when the circles reach the edge of the window.
*/
public void run() {
MovingCircle circle;
Thread myThread = Thread.currentThread();
// Really while animationThread not null.
while(animationThread==myThread) {
for(int j=0; j= NUMIMAGES) {
index = 0;
}
parent.repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break; // Break while loop.
}
}
}
}
*//
TimedAnimation.java An applet that demonstrates animation of an image by using a Timer. Note that Timer is located in the javax.swing package.
import java.awt.*;
import javax.swing.*;
/** An example of performing animation through Swing timers.
* Two timed Dukes are created with different timer periods.
*
*/
public class TimedAnimation extends JApplet {
private static final int NUMDUKES = 2;
private TimedDuke[] dukes;
private int i, index;
public void init() {
dukes = new TimedDuke[NUMDUKES];
setBackground(Color.white);
dukes[0] = new TimedDuke( 1, 100, this);
dukes[1] = new TimedDuke(-1, 500, this);
}
// Start each Duke timer.
public void start() {
for (int i=0; i= NUMIMAGES) {
index = 0;
}
parent.repaint();
}
// Public service to start the timer.
public void startTimer() {
timer.start();
}
// Public service to stop the timer.
public void stopTimer() {
timer.stop();
}
}
**//
Aug 25
Driver class that creates three threaded objects (Counter2) that count from 0 to 4.
/** Try out a few instances of the Counter2 class.
public class Counter2Test {
public static void main(String[] args) {
Counter2 c1 = new Counter2(5);
Counter2 c2 = new Counter2(5);
Counter2 c3 = new Counter2(5);
}
}
/** A Runnable that counts up to a specified
* limit with random pauses in between each count.
public class Counter2 implements Runnable {
private static int totalNum = 0;
private int currentNum, loopLimit;
public Counter2(int loopLimit) {
this.loopLimit = loopLimit;
currentNum = totalNum++;
Thread t = new Thread(this);
t.start();
}
private void pause(double seconds) {
try { Thread.sleep(Math.round(1000.0*seconds)); }
catch(InterruptedException ie) {}
}
public void run() {
for(int i=0; i
Aug 25
Template illustrating the second approach for creating a class with thread behavior.
Template illustrating the second approach for creating a class with thread behavior. In this case, the class implements the Runnable interface while providing a run method for thread execution.
public class ThreadedClass extends AnyClass implements Runnable {
public void run() {
// Thread behavior here.
}
public void startThread() {
Thread t = new Thread(this);
t.start(); // Calls back to the run method in "this."
}
...
}
