home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / code / ch05.txt < prev    next >
Text File  |  1998-12-14  |  18KB  |  842 lines

  1. testActionEvents.java:
  2.  
  3. /*
  4. Example 5.1 This example shows how an action listener
  5.  can be used to coordinate activities among various 
  6. components on an applet
  7.  */
  8.  
  9. import java.awt.*;
  10. import java.awt.event.*;
  11. import java.applet.*;
  12.  
  13. public class testActionEvents extends Applet
  14. {
  15.     public void init()
  16.     {
  17.        super.init();
  18.         setLayout(null);
  19.         btnHello = new Button("Say Hello");
  20.         btnHello.setBounds(36,12,108,43);
  21.         add(btnHello);
  22.         Action btnAction = new Action();
  23.         btnHello.addActionListener(btnAction);
  24.         txtField1 = new TextField();
  25.         txtField1.setBounds(36,96,144,31);
  26.         add(txtField1);
  27.  
  28.     }
  29.  
  30.  
  31.     /* Declare Components */
  32.     Button btnHello;
  33.     TextField txtField1; 
  34.  
  35.     class Action implements ActionListener
  36.     {
  37.         public void actionPerformed(ActionEvent event)
  38.         {
  39.             Object object1 = event.getSource();
  40.             if (object1 == btnHello)
  41.                 btnHelloAction(event);
  42.         }
  43.     }
  44.  
  45.     void btnHelloAction(ActionEvent e)
  46.     {
  47.         txtField1.setText("Hi,Mom");
  48.     }
  49. }
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60. testAdjustEvent.java:
  61.  
  62. /*
  63.     A basic extension of the java.applet.Applet class
  64.  */
  65.  
  66. import java.awt.*;
  67. import java.awt.event.*;
  68. import java.applet.*;
  69.  
  70. public class testAdjustEvent extends Applet
  71. {
  72.     void ScrollValueChanged( AdjustmentEvent event)
  73.     {
  74.         int intValue = scoreBar.getValue();
  75.         String strValue = String.valueOf(intValue);
  76.         
  77.         txtScore.setText(strValue);
  78.     }
  79.     
  80.     public void init()
  81.     {
  82.           super.init();
  83.  
  84.       setLayout(null);
  85.       label1 = new Label("Score:", Label.RIGHT);
  86.       label1.setBounds(36,36,60,21);
  87.       add(label1);
  88.       txtScore = new TextField();
  89.       txtScore.setEditable(false);
  90.       txtScore.setBounds(108,36,48,23);
  91.       add(txtScore);
  92.       scoreBar = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,100);
  93.       scoreBar.setBounds(180,36,137,26);
  94.       add(scoreBar);
  95.       txtScore.setText(String.valueOf(scoreBar.getValue()));
  96.  
  97.       Adjustment1 lAdjustment = new Adjustment1();
  98.       scoreBar.addAdjustmentListener(lAdjustment);
  99.     }
  100.  
  101.     
  102.     Label label1;
  103.     TextField txtScore;
  104.     Scrollbar scoreBar;
  105.     
  106.     class Adjustment1 implements AdjustmentListener
  107.     {
  108.         public void adjustmentValueChanged(AdjustmentEvent event)
  109.         {
  110.         Object object1 = event.getSource();
  111.         if (object1==scoreBar)
  112.            ScrollValueChanged(event);
  113.         }
  114.     }
  115. }
  116.  
  117.  
  118.  
  119.  
  120.  
  121.  
  122.  
  123.  
  124.  
  125. Doodle.java:
  126.  
  127. import java.applet.Applet;
  128. import java.awt.*;
  129. import java.awt.event.*;
  130.  
  131. /**
  132.  * The ColorBar class displays a color bar for color selection.
  133.  */
  134. class ColorBar {
  135.  
  136. /*
  137.  * the top-left coordinate of the color bar
  138.  */
  139. int xpos, ypos;
  140.  
  141. /*
  142.  * the width and height of the color bar
  143.  */
  144. int width, height;
  145.  
  146. /*
  147.  * the current color selection index into the colors array
  148.  */
  149. int selectedColor = 3;
  150.  
  151. /*
  152.  * the array of colors available for selection
  153.  */
  154. static Color colors[] = {
  155.     Color.white, Color.gray, Color.red, Color.pink,
  156.     Color.orange, Color.yellow, Color.green, Color.magenta,
  157.     Color.cyan, Color.blue
  158. };
  159.  
  160. /**
  161.  * Create the color bar
  162.  */
  163. public ColorBar (int x, int y, int w, int h) {
  164.  
  165.     xpos = x;
  166.     ypos = y;
  167.     width = w;
  168.     height = h;
  169. }
  170.  
  171. /**
  172.  * Paint the color bar
  173.  * @param g - destination graphics object
  174.  */
  175. void paint (Graphics g) {
  176.  
  177.     int x, y;    // position of each color box
  178.     int w, h;    // size of each color box
  179.  
  180.     for (int i=0; i<colors.length; i+=1) {
  181.         w = width; 
  182.         h = height/colors.length;
  183.         x = xpos;
  184.         y = ypos + (i * h);
  185.         g.setColor (Color.black);
  186.         g.fillRect (x, y, w, h);
  187.         if (i == selectedColor) {
  188.             x += 5;
  189.             y += 5;
  190.             w -= 10;
  191.             h -= 10;
  192.         } else {
  193.             x += 1;
  194.             y += 1;
  195.             w -= 2;
  196.             h -= 2;
  197.         }
  198.         g.setColor (colors[i]);
  199.         g.fillRect (x, y, w, h);
  200.     }
  201. }
  202.  
  203. /**
  204.  * Check to see if the mouse is inside a palette box.
  205.  * If so, set selectedColor and return true,
  206.  *        otherwise return false.
  207.  * @param x, y - x and y position of mouse
  208.  */
  209. boolean inside (int x, int y) {
  210.  
  211.     int i, h;
  212.  
  213.     if (x < xpos || x > xpos+width) return false;
  214.     if (y < ypos || y > ypos+height) return false;
  215.  
  216.     h = height/colors.length;
  217.     for (i=0; i<colors.length; i+=1) {
  218.         if (y < (i+1)*h+ypos) {
  219.             selectedColor = i;
  220.             return true;
  221.         }
  222.     }
  223.     return false;
  224. }
  225.  
  226. }
  227.  
  228. /**
  229.  * The Doodle applet implements a drawable surface
  230.  * with a limited choice of colors to draw with.
  231.  */
  232. public class Doodle extends Applet
  233.         implements MouseListener, MouseMotionListener
  234. {
  235.  
  236. /*
  237.  * the maximum number of points that can be
  238.  * saved in the xpoints, ypoints, and color arrays
  239.  */
  240. static final int MaxPoints = 1000;
  241.  
  242. /*
  243.  * arrays to hold the points where the user draws
  244.  */
  245. int xpoints[] = new int[MaxPoints];
  246. int ypoints[] = new int[MaxPoints];
  247.  
  248. /*
  249.  * the color of each point
  250.  */
  251. int color[] = new int[MaxPoints];
  252.  
  253. /*
  254.  * used to keep track of the previous mouse
  255.  * click to avoid filling arrays with the
  256.  * same point
  257.  */
  258. int lastx;
  259. int lasty;
  260.  
  261. /*
  262.  * the number of points in the arrays
  263.  */
  264. int npoints = 0;
  265. ColorBar colorBar;
  266. boolean inColorBar;
  267.  
  268. /**
  269.  * Initialize the drawing space
  270.  */
  271. public void init () {
  272.  
  273.     setBackground(Color.white);
  274.     colorBar = new ColorBar (10, 10, 30, 200);
  275.     addMouseListener(this);
  276.     addMouseMotionListener(this);
  277. }
  278.  
  279. /**
  280.  * Redisplay the drawing space
  281.  * @param g - destination graphics object
  282.  */
  283. public void update (Graphics g) {
  284.  
  285.     int i; 
  286.  
  287.     for (i=0; i<npoints; i+=1) {
  288.         g.setColor (colorBar.colors[color[i]]);
  289.         g.fillOval (xpoints[i]-5, ypoints[i]-5, 10, 10);
  290.     }
  291.     colorBar.paint (g);
  292. }
  293.  
  294. /**
  295.  * Repaint the drawing space when required
  296.  * @param g - destination graphics object
  297.  */
  298. public void paint (Graphics g) {
  299.  
  300.     update (g);
  301. }
  302.  
  303.  
  304.  
  305. public void mouseClicked(MouseEvent e){}
  306. public void mouseEntered(MouseEvent e){}
  307. public void mouseExited(MouseEvent e){}
  308. public void mouseReleased(MouseEvent e){}
  309. public void mouseMoved(MouseEvent e){}
  310.  
  311. public void mousePressed(MouseEvent e)
  312. {
  313.     int x =e.getX();
  314.     int y =e.getY();
  315.  
  316.     if (colorBar.inside (x, y)) {
  317.         inColorBar = true;
  318.         repaint ();
  319.     }
  320.     inColorBar = false;
  321.     if (npoints < MaxPoints) {
  322.         lastx = x;
  323.         lasty = y;
  324.         xpoints[npoints] = x;
  325.         ypoints[npoints] = y;
  326.         color[npoints] = colorBar.selectedColor; 
  327.         npoints += 1;
  328.         repaint();
  329.         return;
  330.     }
  331. }
  332.  
  333. public void mouseDragged(MouseEvent e)
  334. {
  335.     if (inColorBar) return;
  336.  
  337.     int x =e.getX();
  338.     int y =e.getY();
  339.  
  340.     if ((x != lastx || y != lasty) && npoints < MaxPoints) {
  341.         lastx = x;
  342.         lasty = y; 
  343.         xpoints[npoints] = x;
  344.         ypoints[npoints] = y;
  345.         color[npoints] = colorBar.selectedColor;
  346.         npoints += 1;
  347.         repaint ();
  348.     }
  349.  
  350. }
  351.  
  352. /**
  353.  * The main method allows this class to be run as an application
  354.  * in addition to being run as an applet.
  355.  * @param args - command-line arguments
  356.  */
  357.  
  358. public static void main (String args[]) {
  359.  
  360.     Frame f = new Frame ("Doodle");
  361.     Doodle doodle = new Doodle ();
  362.        WindowListener l = new WindowAdapter()
  363.        {
  364.             public void windowClosing(WindowEvent e)
  365.             {
  366.                 System.exit(0);
  367.             }//windowClosing
  368.        };//WindowListener
  369.        f.addWindowListener(l);
  370.  
  371.  
  372.     f.setSize (410, 430); 
  373.     f.add ("Center", doodle);
  374.     f.show ();
  375.     doodle.init ();
  376. }
  377. }
  378.  
  379.  
  380.  
  381.  
  382.  
  383.  
  384.  
  385. Windows1.java:
  386.  
  387. import java.util.*;
  388. import java.awt.*;
  389. import java.awt.event.*;
  390. import javax.swing.*;
  391. import javax.swing.text.*;
  392.  
  393. public class Windows1 extends Object implements WindowListener
  394. {
  395.     public void windowOpened(WindowEvent e)
  396.     {
  397.         System.out.println("Window opened.");
  398.     }
  399.  
  400.     public void windowClosing(WindowEvent e)
  401.     {
  402.         System.out.println("Window closing.");
  403.  System.exit(0);
  404.  
  405.     }
  406.  
  407.     public void windowClosed(WindowEvent e)
  408.     {
  409.         System.out.println("Window closed.");
  410.     }
  411.  
  412.     public void windowIconified(WindowEvent e)
  413.     {
  414.         System.out.println("Window iconified.");
  415.     }
  416.  
  417.     public void windowDeiconified(WindowEvent e)
  418.     {
  419.         System.out.println("Window deiconified.");
  420.     }
  421.  
  422.     public void windowActivated(WindowEvent e)
  423.     {
  424.  
  425.         System.out.println("Window activated.");
  426.     }
  427.  
  428.     public void windowDeactivated(WindowEvent e)
  429.     {
  430.         System.out.println("Window deactivated");
  431.     }
  432.  
  433.     public static void main(String s[])
  434.     {
  435.         JFrame frame = new JFrame("Windows1");
  436.  
  437.         frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  438.         frame.addWindowListener(new Windows1());
  439.  
  440.  
  441.  
  442. frame.getContentPane().add( new Label("Hello World"), "Center");
  443.  
  444.         frame.pack();
  445.         frame.setVisible(true);
  446.     }
  447.  
  448.  
  449. }
  450.  
  451.  
  452.  
  453.  
  454.  
  455.  
  456.  
  457. ScrollApp.java:
  458.  
  459. import java.applet.Applet;
  460. import java.awt.*;
  461.  
  462. class Scroll {
  463.  
  464. int xstart, ystart;
  465. int width, height;
  466. String text;
  467. int deltaX, deltaY;
  468. int xpos, ypos;
  469. Color color;
  470.  
  471. /**
  472.  * Text scrolls in different directions.
  473.  * @param xpos      initial x position
  474.  * @param ypos      initial y position
  475.  * @param deltax    velocity in x direction
  476.  * @param deltay    velocity in y direction
  477.  * @param width     bounding point for window panel width
  478.  * @param height    bounding point for window panel height
  479.  * @param text      text that is scrolled on the window
  480.  * @param color     color of the text
  481.  */
  482. public Scroll (int x, int y, int dx, int dy, int w,int h, String t, Color c) {
  483.  
  484.     xstart = x;
  485.     ystart = y;
  486.     width = w;
  487.     height = h;
  488.     text = t;
  489.     deltaX = dx;
  490.     deltaY = dy;
  491.     color = c;
  492.     xpos = xstart;
  493.     ypos = ystart;
  494. }
  495.  
  496. /**
  497.  * Called from update() in response to repaint()
  498.  * @param g - destination graphics object
  499.  */
  500. void paint (Graphics g) {
  501.  
  502.     g.setColor (color);
  503.     g.drawString (text, xpos, ypos);
  504.     xpos += deltaX;
  505.     ypos += deltaY;
  506.  
  507.     FontMetrics fm = g.getFontMetrics ();
  508.     int textw = fm.stringWidth (text);
  509.     int texth = fm.getHeight ();
  510.     if (deltaX < 0 && xpos < -textw) xpos = xstart;
  511.     if (deltaX > 0 && xpos > width) xpos = xstart;
  512.     if (deltaY < 0 && ypos < 0) ypos = ystart;
  513.     if (deltaY > 0 && ypos > height+texth) ypos = ystart;
  514. }
  515. } // Class Scroll
  516.  
  517.  
  518. /*
  519.  * The applet/application class
  520.  */
  521. public class ScrollApp extends Applet implements Runnable{
  522.  
  523. /*
  524.  * Width and height of the bounding panel
  525.  */
  526. int width, height;
  527.  
  528. /*
  529.  * Instance of a left-scrolling Scroll object
  530.  */
  531. Scroll left;
  532. String input_text;
  533. Font font = new Font("Helvetica",1,24);
  534. Thread thread;
  535.  
  536. /*
  537.  * Called when the applet is loaded
  538.  * Create instances of FIFO, Source, Sink, and Thread.
  539.  */
  540. public void init () {
  541.  
  542.     input_text=getParameter("text");
  543.     Dimension d = getSize ();
  544.  
  545.     width = d.width;
  546.     height = d.height;
  547.  
  548.     left = new Scroll (400, 50, -5, 0, width, height,
  549.         input_text, Color.red);
  550. } // init()
  551.  
  552. /*
  553.  * Start the graphics update thread.
  554.  */
  555. public void start() {
  556.  
  557.     thread = new Thread(this);
  558.     thread.start();
  559. } // start()
  560.  
  561. /*
  562.  * The graphics update thread
  563.  * Call repaint every 100 ms. 
  564.  */
  565. public void run() {
  566.  
  567.     while (true) {
  568.         try {
  569.             Thread.sleep(100);
  570.         } catch (InterruptedException e) { }
  571.         repaint();
  572.     }
  573. } // run()
  574.  
  575. /*
  576.  * Stop the graphics update thread.
  577.  */
  578. public void stop() {
  579.  
  580.     if (thread != null)
  581.     thread = null;
  582. } // stop()
  583.  
  584. /**
  585.  * Called from update() in response to repaint()
  586.  * @param g - destination graphics object
  587.  */
  588. public void paint (Graphics g) {
  589.  
  590.     g.setFont(font);
  591.     left.paint (g);
  592. } // paint()
  593. } // class ScrollApp
  594.  
  595.  
  596.  
  597.  
  598.  
  599.  
  600. ScrollApp.java:
  601.  
  602. import java.applet.Applet;
  603. import java.awt.*;
  604. import java.util.*;
  605.  
  606. class Scroll {
  607.  
  608. int xstart, ystart;
  609. int width, height;
  610. String text;
  611. int deltaX, deltaY;
  612. int xpos, ypos;
  613. Color color;
  614.  
  615. /**
  616.  * Text scrolls in different directions.
  617.  * @param xpos          initial x position
  618.  * @param ypos          initial y position
  619.  * @param deltax        velocity in x direction
  620.  * @param deltay        velocity in y direction
  621.  * @param width         bounding point for window panel width
  622.  * @param height        bounding point for window panel height
  623.  * @param text          text that is scrolled on the window
  624.  * @param color         color of the text
  625.  */
  626. public Scroll (int x, int y, int dx, int dy, int w,σ
  627.  int h, String t, Color ?c) {
  628.  
  629.     xstart = x;
  630.     ystart = y;
  631.     width = w;
  632.     height = h;
  633.     text = t;
  634.     deltaX = dx;
  635.     deltaY = dy;
  636.     color = c;
  637.     xpos = xstart;
  638.     ypos = ystart;
  639. }
  640.  
  641. /**
  642.  * Called from update() in response to repaint()
  643.  * @param g - destination graphics object
  644.  */
  645. void paint (Graphics g) {
  646.  
  647.     g.setColor (color);
  648.     g.drawString (text, xpos, ypos);
  649.     xpos += deltaX;
  650.     ypos += deltaY; 
  651.  
  652.     FontMetrics fm = g.getFontMetrics ();
  653.     int textw = fm.stringWidth (text);
  654.     int texth = fm.getHeight ();
  655.     if (deltaX < 0 && xpos < -textw) xpos = xstart;
  656.     if (deltaX > 0 && xpos > width) xpos = xstart;
  657.     if (deltaY < 0 && ypos < 0) ypos = ystart;
  658.     if (deltaY > 0 && ypos > height+texth) ypos = ystart;
  659. }
  660. } // Class Scroll
  661.  
  662. /*
  663.  * The applet class
  664.  */
  665. public class ScrollApp extends Applet implements Runnable {
  666.  
  667. /*
  668.  * Width and height of the bounding panel
  669.  */
  670. int width, height;
  671.  
  672. /*
  673.  * The number of scrolling objects
  674.  */
  675. int nscroll = 0;
  676.  
  677. /*
  678.  * Array of scrolling objects
  679.  */
  680. Scroll scr[] = new Scroll[5];
  681. Font font = new Font("Helvetica",1,24);
  682. Thread thread;
  683.  
  684. /*
  685.  * Called when the applet is loaded
  686.  * Parses applet parameters
  687.  */
  688. public void init () {
  689.  
  690.     String scr_text[] = {"test1","test2","test3","test4","test5"};
  691.     int scr_xvel[] =  {-5,5,0,0,7};
  692.     int scr_yvel[] =  {0,0,-5,5,3};
  693.     int scr_xpos[] =  {400,0,100,200,0};
  694.     int scr_ypos[] =  {50,150,200,0,0};
  695.     int scr_red[] =   {255,0,0,100,200};
  696.     int scr_green[] = {0,255,0,200,100};
  697.     int scr_blue[] =  {0,0,255,50,50};
  698.     Color scr_color[] = new Color[5];
  699.     int i; 
  700.     Dimension d = getSize ();
  701.  
  702.     width = d.width;
  703.     height = d.height;
  704.     for (i=1; i<=5; i+=1) {
  705.         String param, token;
  706.         int j = 0;
  707.  
  708.         param = getParameter ("Scroll"+i);
  709.         if (param == null) break;
  710.  
  711.         StringTokenizer st = new StringTokenizer (param, ",");
  712.         token = st.nextToken ();
  713.         scr_text[nscroll] = token; 
  714.  
  715.         token = st.nextToken ();
  716.         try {
  717.             j = Integer.valueOf (token).intValue();
  718.         } catch (NumberFormatException e){
  719.         }
  720.  
  721.         switch (j) {
  722.             case 0: //Scroll left.
  723.                 scr_xvel[nscroll] = -5;
  724.                 scr_yvel[nscroll] = 0;
  725.                 scr_xpos[nscroll] = 400;
  726.                 scr_ypos[nscroll] = 50;
  727.                 break;
  728.  
  729.             case 1: //Scroll right.
  730.                 scr_xvel[nscroll] = 5;
  731.                 scr_yvel[nscroll] = 0;
  732.                 scr_xpos[nscroll] = 0;
  733.                 scr_ypos[nscroll] = 150;
  734.                 break;
  735.  
  736.             case 2: //Scroll up.
  737.                 scr_xvel[nscroll] = 0;
  738.                 scr_yvel[nscroll] = -5;
  739.                 scr_xpos[nscroll] = 100;
  740.                 scr_ypos[nscroll] = 200;
  741.                 break;
  742.  
  743.             case 3: //Scroll down.
  744.                 scr_xvel[nscroll] = 0;
  745.                 scr_yvel[nscroll] = 5;
  746.                 scr_xpos[nscroll] = 200;
  747.                 scr_ypos[nscroll] = 0;
  748.                 break; 
  749.  
  750.             case 4: //Scroll diagonally.
  751.                 scr_xvel[nscroll] = 7;
  752.                 scr_yvel[nscroll] = 3;
  753.                 scr_xpos[nscroll] = 0;
  754.                 scr_ypos[nscroll] = 0;
  755.                 break;
  756.         }
  757.  
  758.         token = st.nextToken ();
  759.         try {
  760.             scr_red[nscroll] = Integer.valueOf(token).intValue();
  761.         } catch (NumberFormatException e) {
  762.         }
  763.  
  764.         token = st.nextToken ();
  765.         try {
  766.             scr_green[nscroll] = Integer.valueOf(token).intValue();
  767.         } catch (NumberFormatException e) {
  768.         }
  769.  
  770.         token = st.nextToken ();
  771.         try {
  772.             scr_blue[nscroll] = Integer.valueOf(token).intValue();
  773.         } catch (NumberFormatException e) {
  774.         }
  775.  
  776.         scr_color[nscroll] = new Color(scr_red[nscroll],
  777.             scr_green[nscroll], scr_blue[nscroll]);
  778.         nscroll +=1;
  779.     }
  780.     for (i=0; i<nscroll; i+=1) {
  781.         scr[i] = new Scroll (scr_xpos[i], scr_ypos[i],
  782.             scr_xvel[i], scr_yvel[i], width, height,
  783.             scr_text[i], scr_color[i]);
  784.     }
  785. } // init()
  786.  
  787. /*
  788.  * Start the graphics update thread. 
  789.  */
  790. public void start() {
  791.  
  792.     thread = new Thread(this);
  793.     thread.start ();
  794. } // start()
  795.  
  796. /*
  797.  * The graphics update thread
  798.  * Call repaint every 100 ms.
  799.  */
  800. public void run() {
  801.  
  802.     while (true) {
  803.         try {
  804.             Thread.sleep(100);
  805.         } catch (InterruptedException e) { }
  806.         repaint();
  807.     }
  808. } // run()
  809.  
  810. /*
  811.  * Stop the graphics update thread.
  812.  */
  813. public void stop() {
  814.  
  815. if (thread != null)
  816.    thread = null;
  817.  
  818.  
  819. } // stop();
  820.  
  821. /**
  822.  * Called from update() in response to repaint()
  823.  * @param g - destination graphics object
  824.  */
  825. public void paint (Graphics g) {
  826.  
  827.     int i;
  828.  
  829.     g.setFont(font);
  830.     for (i=0; i<nscroll; i+=1) {
  831.         scr[i].paint (g);
  832.     }
  833. } // paint()
  834. } // Class ScrollApp
  835.  
  836.  
  837.  
  838.  
  839.  
  840.  
  841.  
  842.