home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java 1.2 How-To
/
JavaHowTo.iso
/
code
/
ch05.txt
< prev
next >
Wrap
Text File
|
1998-12-14
|
18KB
|
842 lines
testActionEvents.java:
/*
Example 5.1 This example shows how an action listener
can be used to coordinate activities among various
components on an applet
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class testActionEvents extends Applet
{
public void init()
{
super.init();
setLayout(null);
btnHello = new Button("Say Hello");
btnHello.setBounds(36,12,108,43);
add(btnHello);
Action btnAction = new Action();
btnHello.addActionListener(btnAction);
txtField1 = new TextField();
txtField1.setBounds(36,96,144,31);
add(txtField1);
}
/* Declare Components */
Button btnHello;
TextField txtField1;
class Action implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object object1 = event.getSource();
if (object1 == btnHello)
btnHelloAction(event);
}
}
void btnHelloAction(ActionEvent e)
{
txtField1.setText("Hi,Mom");
}
}
testAdjustEvent.java:
/*
A basic extension of the java.applet.Applet class
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class testAdjustEvent extends Applet
{
void ScrollValueChanged( AdjustmentEvent event)
{
int intValue = scoreBar.getValue();
String strValue = String.valueOf(intValue);
txtScore.setText(strValue);
}
public void init()
{
super.init();
setLayout(null);
label1 = new Label("Score:", Label.RIGHT);
label1.setBounds(36,36,60,21);
add(label1);
txtScore = new TextField();
txtScore.setEditable(false);
txtScore.setBounds(108,36,48,23);
add(txtScore);
scoreBar = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,100);
scoreBar.setBounds(180,36,137,26);
add(scoreBar);
txtScore.setText(String.valueOf(scoreBar.getValue()));
Adjustment1 lAdjustment = new Adjustment1();
scoreBar.addAdjustmentListener(lAdjustment);
}
Label label1;
TextField txtScore;
Scrollbar scoreBar;
class Adjustment1 implements AdjustmentListener
{
public void adjustmentValueChanged(AdjustmentEvent event)
{
Object object1 = event.getSource();
if (object1==scoreBar)
ScrollValueChanged(event);
}
}
}
Doodle.java:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/**
* The ColorBar class displays a color bar for color selection.
*/
class ColorBar {
/*
* the top-left coordinate of the color bar
*/
int xpos, ypos;
/*
* the width and height of the color bar
*/
int width, height;
/*
* the current color selection index into the colors array
*/
int selectedColor = 3;
/*
* the array of colors available for selection
*/
static Color colors[] = {
Color.white, Color.gray, Color.red, Color.pink,
Color.orange, Color.yellow, Color.green, Color.magenta,
Color.cyan, Color.blue
};
/**
* Create the color bar
*/
public ColorBar (int x, int y, int w, int h) {
xpos = x;
ypos = y;
width = w;
height = h;
}
/**
* Paint the color bar
* @param g - destination graphics object
*/
void paint (Graphics g) {
int x, y; // position of each color box
int w, h; // size of each color box
for (int i=0; i<colors.length; i+=1) {
w = width;
h = height/colors.length;
x = xpos;
y = ypos + (i * h);
g.setColor (Color.black);
g.fillRect (x, y, w, h);
if (i == selectedColor) {
x += 5;
y += 5;
w -= 10;
h -= 10;
} else {
x += 1;
y += 1;
w -= 2;
h -= 2;
}
g.setColor (colors[i]);
g.fillRect (x, y, w, h);
}
}
/**
* Check to see if the mouse is inside a palette box.
* If so, set selectedColor and return true,
* otherwise return false.
* @param x, y - x and y position of mouse
*/
boolean inside (int x, int y) {
int i, h;
if (x < xpos || x > xpos+width) return false;
if (y < ypos || y > ypos+height) return false;
h = height/colors.length;
for (i=0; i<colors.length; i+=1) {
if (y < (i+1)*h+ypos) {
selectedColor = i;
return true;
}
}
return false;
}
}
/**
* The Doodle applet implements a drawable surface
* with a limited choice of colors to draw with.
*/
public class Doodle extends Applet
implements MouseListener, MouseMotionListener
{
/*
* the maximum number of points that can be
* saved in the xpoints, ypoints, and color arrays
*/
static final int MaxPoints = 1000;
/*
* arrays to hold the points where the user draws
*/
int xpoints[] = new int[MaxPoints];
int ypoints[] = new int[MaxPoints];
/*
* the color of each point
*/
int color[] = new int[MaxPoints];
/*
* used to keep track of the previous mouse
* click to avoid filling arrays with the
* same point
*/
int lastx;
int lasty;
/*
* the number of points in the arrays
*/
int npoints = 0;
ColorBar colorBar;
boolean inColorBar;
/**
* Initialize the drawing space
*/
public void init () {
setBackground(Color.white);
colorBar = new ColorBar (10, 10, 30, 200);
addMouseListener(this);
addMouseMotionListener(this);
}
/**
* Redisplay the drawing space
* @param g - destination graphics object
*/
public void update (Graphics g) {
int i;
for (i=0; i<npoints; i+=1) {
g.setColor (colorBar.colors[color[i]]);
g.fillOval (xpoints[i]-5, ypoints[i]-5, 10, 10);
}
colorBar.paint (g);
}
/**
* Repaint the drawing space when required
* @param g - destination graphics object
*/
public void paint (Graphics g) {
update (g);
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
int x =e.getX();
int y =e.getY();
if (colorBar.inside (x, y)) {
inColorBar = true;
repaint ();
}
inColorBar = false;
if (npoints < MaxPoints) {
lastx = x;
lasty = y;
xpoints[npoints] = x;
ypoints[npoints] = y;
color[npoints] = colorBar.selectedColor;
npoints += 1;
repaint();
return;
}
}
public void mouseDragged(MouseEvent e)
{
if (inColorBar) return;
int x =e.getX();
int y =e.getY();
if ((x != lastx || y != lasty) && npoints < MaxPoints) {
lastx = x;
lasty = y;
xpoints[npoints] = x;
ypoints[npoints] = y;
color[npoints] = colorBar.selectedColor;
npoints += 1;
repaint ();
}
}
/**
* The main method allows this class to be run as an application
* in addition to being run as an applet.
* @param args - command-line arguments
*/
public static void main (String args[]) {
Frame f = new Frame ("Doodle");
Doodle doodle = new Doodle ();
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}//windowClosing
};//WindowListener
f.addWindowListener(l);
f.setSize (410, 430);
f.add ("Center", doodle);
f.show ();
doodle.init ();
}
}
Windows1.java:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class Windows1 extends Object implements WindowListener
{
public void windowOpened(WindowEvent e)
{
System.out.println("Window opened.");
}
public void windowClosing(WindowEvent e)
{
System.out.println("Window closing.");
System.exit(0);
}
public void windowClosed(WindowEvent e)
{
System.out.println("Window closed.");
}
public void windowIconified(WindowEvent e)
{
System.out.println("Window iconified.");
}
public void windowDeiconified(WindowEvent e)
{
System.out.println("Window deiconified.");
}
public void windowActivated(WindowEvent e)
{
System.out.println("Window activated.");
}
public void windowDeactivated(WindowEvent e)
{
System.out.println("Window deactivated");
}
public static void main(String s[])
{
JFrame frame = new JFrame("Windows1");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new Windows1());
frame.getContentPane().add( new Label("Hello World"), "Center");
frame.pack();
frame.setVisible(true);
}
}
ScrollApp.java:
import java.applet.Applet;
import java.awt.*;
class Scroll {
int xstart, ystart;
int width, height;
String text;
int deltaX, deltaY;
int xpos, ypos;
Color color;
/**
* Text scrolls in different directions.
* @param xpos initial x position
* @param ypos initial y position
* @param deltax velocity in x direction
* @param deltay velocity in y direction
* @param width bounding point for window panel width
* @param height bounding point for window panel height
* @param text text that is scrolled on the window
* @param color color of the text
*/
public Scroll (int x, int y, int dx, int dy, int w,int h, String t, Color c) {
xstart = x;
ystart = y;
width = w;
height = h;
text = t;
deltaX = dx;
deltaY = dy;
color = c;
xpos = xstart;
ypos = ystart;
}
/**
* Called from update() in response to repaint()
* @param g - destination graphics object
*/
void paint (Graphics g) {
g.setColor (color);
g.drawString (text, xpos, ypos);
xpos += deltaX;
ypos += deltaY;
FontMetrics fm = g.getFontMetrics ();
int textw = fm.stringWidth (text);
int texth = fm.getHeight ();
if (deltaX < 0 && xpos < -textw) xpos = xstart;
if (deltaX > 0 && xpos > width) xpos = xstart;
if (deltaY < 0 && ypos < 0) ypos = ystart;
if (deltaY > 0 && ypos > height+texth) ypos = ystart;
}
} // Class Scroll
/*
* The applet/application class
*/
public class ScrollApp extends Applet implements Runnable{
/*
* Width and height of the bounding panel
*/
int width, height;
/*
* Instance of a left-scrolling Scroll object
*/
Scroll left;
String input_text;
Font font = new Font("Helvetica",1,24);
Thread thread;
/*
* Called when the applet is loaded
* Create instances of FIFO, Source, Sink, and Thread.
*/
public void init () {
input_text=getParameter("text");
Dimension d = getSize ();
width = d.width;
height = d.height;
left = new Scroll (400, 50, -5, 0, width, height,
input_text, Color.red);
} // init()
/*
* Start the graphics update thread.
*/
public void start() {
thread = new Thread(this);
thread.start();
} // start()
/*
* The graphics update thread
* Call repaint every 100 ms.
*/
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
repaint();
}
} // run()
/*
* Stop the graphics update thread.
*/
public void stop() {
if (thread != null)
thread = null;
} // stop()
/**
* Called from update() in response to repaint()
* @param g - destination graphics object
*/
public void paint (Graphics g) {
g.setFont(font);
left.paint (g);
} // paint()
} // class ScrollApp
ScrollApp.java:
import java.applet.Applet;
import java.awt.*;
import java.util.*;
class Scroll {
int xstart, ystart;
int width, height;
String text;
int deltaX, deltaY;
int xpos, ypos;
Color color;
/**
* Text scrolls in different directions.
* @param xpos initial x position
* @param ypos initial y position
* @param deltax velocity in x direction
* @param deltay velocity in y direction
* @param width bounding point for window panel width
* @param height bounding point for window panel height
* @param text text that is scrolled on the window
* @param color color of the text
*/
public Scroll (int x, int y, int dx, int dy, int w,σ
int h, String t, Color ?c) {
xstart = x;
ystart = y;
width = w;
height = h;
text = t;
deltaX = dx;
deltaY = dy;
color = c;
xpos = xstart;
ypos = ystart;
}
/**
* Called from update() in response to repaint()
* @param g - destination graphics object
*/
void paint (Graphics g) {
g.setColor (color);
g.drawString (text, xpos, ypos);
xpos += deltaX;
ypos += deltaY;
FontMetrics fm = g.getFontMetrics ();
int textw = fm.stringWidth (text);
int texth = fm.getHeight ();
if (deltaX < 0 && xpos < -textw) xpos = xstart;
if (deltaX > 0 && xpos > width) xpos = xstart;
if (deltaY < 0 && ypos < 0) ypos = ystart;
if (deltaY > 0 && ypos > height+texth) ypos = ystart;
}
} // Class Scroll
/*
* The applet class
*/
public class ScrollApp extends Applet implements Runnable {
/*
* Width and height of the bounding panel
*/
int width, height;
/*
* The number of scrolling objects
*/
int nscroll = 0;
/*
* Array of scrolling objects
*/
Scroll scr[] = new Scroll[5];
Font font = new Font("Helvetica",1,24);
Thread thread;
/*
* Called when the applet is loaded
* Parses applet parameters
*/
public void init () {
String scr_text[] = {"test1","test2","test3","test4","test5"};
int scr_xvel[] = {-5,5,0,0,7};
int scr_yvel[] = {0,0,-5,5,3};
int scr_xpos[] = {400,0,100,200,0};
int scr_ypos[] = {50,150,200,0,0};
int scr_red[] = {255,0,0,100,200};
int scr_green[] = {0,255,0,200,100};
int scr_blue[] = {0,0,255,50,50};
Color scr_color[] = new Color[5];
int i;
Dimension d = getSize ();
width = d.width;
height = d.height;
for (i=1; i<=5; i+=1) {
String param, token;
int j = 0;
param = getParameter ("Scroll"+i);
if (param == null) break;
StringTokenizer st = new StringTokenizer (param, ",");
token = st.nextToken ();
scr_text[nscroll] = token;
token = st.nextToken ();
try {
j = Integer.valueOf (token).intValue();
} catch (NumberFormatException e){
}
switch (j) {
case 0: //Scroll left.
scr_xvel[nscroll] = -5;
scr_yvel[nscroll] = 0;
scr_xpos[nscroll] = 400;
scr_ypos[nscroll] = 50;
break;
case 1: //Scroll right.
scr_xvel[nscroll] = 5;
scr_yvel[nscroll] = 0;
scr_xpos[nscroll] = 0;
scr_ypos[nscroll] = 150;
break;
case 2: //Scroll up.
scr_xvel[nscroll] = 0;
scr_yvel[nscroll] = -5;
scr_xpos[nscroll] = 100;
scr_ypos[nscroll] = 200;
break;
case 3: //Scroll down.
scr_xvel[nscroll] = 0;
scr_yvel[nscroll] = 5;
scr_xpos[nscroll] = 200;
scr_ypos[nscroll] = 0;
break;
case 4: //Scroll diagonally.
scr_xvel[nscroll] = 7;
scr_yvel[nscroll] = 3;
scr_xpos[nscroll] = 0;
scr_ypos[nscroll] = 0;
break;
}
token = st.nextToken ();
try {
scr_red[nscroll] = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
}
token = st.nextToken ();
try {
scr_green[nscroll] = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
}
token = st.nextToken ();
try {
scr_blue[nscroll] = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
}
scr_color[nscroll] = new Color(scr_red[nscroll],
scr_green[nscroll], scr_blue[nscroll]);
nscroll +=1;
}
for (i=0; i<nscroll; i+=1) {
scr[i] = new Scroll (scr_xpos[i], scr_ypos[i],
scr_xvel[i], scr_yvel[i], width, height,
scr_text[i], scr_color[i]);
}
} // init()
/*
* Start the graphics update thread.
*/
public void start() {
thread = new Thread(this);
thread.start ();
} // start()
/*
* The graphics update thread
* Call repaint every 100 ms.
*/
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
repaint();
}
} // run()
/*
* Stop the graphics update thread.
*/
public void stop() {
if (thread != null)
thread = null;
} // stop();
/**
* Called from update() in response to repaint()
* @param g - destination graphics object
*/
public void paint (Graphics g) {
int i;
g.setFont(font);
for (i=0; i<nscroll; i+=1) {
scr[i].paint (g);
}
} // paint()
} // Class ScrollApp