20-CS-694 Advanced Programming Techniques Spring 2012

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

     Previous      Next      Applet Source      All lectures

JButton Test

/*          Click a button - see a result             */
/*          -----------------------------             */
/*  The frame holds a Canvas and a Panel.  The Panel  */
/*  is for three buttons labeled "One", "Two", and    */
/*  "Three".  When a button is clicked, a word is     */
/*  written to the Canvas.  If the "One" button is    */
/*  clicked, the word "ONE" is written, and so on.    */

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ButtonsApplet extends Applet implements ActionListener {
   Button b1, b2, b3;
   Panel p;           // p holds three buttons (b1, b2, b3)
   Canvas q;          // q holds a word (ONE, TWO, THREE)
   String s="";       // the word appearing in q
   Font f;            // the font the word is drawn in
   FontMetrics fm;    // font metric for font f

   public void init () {
      // initialize a Panel with buttons
      p = new Panel();
      p.setLayout(new GridLayout(1,3));
      p.add(b1 = new Button("One"));
      p.add(b2 = new Button("Two"));
      p.add(b3 = new Button("Three"));

      // initialize a Canvas
      q = new Canvas();

      // set the font for the Canvas
      q.setFont(f = new Font("TimesRoman", Font.BOLD, 28));
      fm = getFontMetrics(f);
   public void actionPerformed (ActionEvent evt) {
      int xstart, ystart;

      // Erase the old word written in Canvas q
      Color bgcolor = getBackground();
      xstart = (this.getSize().width - fm.stringWidth(s))/2;
      ystart = (this.getSize().height - fm.getHeight())/2;
      Graphics g = q.getGraphics();
      g.drawString(s, xstart, ystart);

      // Set the new word for Canvas q
      if (evt.getSource() == b1) s = "ONE";
      else if (evt.getSource() == b2) s = "TWO";
      else if (evt.getSource() == b3) s = "THREE";
      // Write the word to Canvas q
      xstart = (this.getSize().width - fm.stringWidth(s))/2;
      ystart = (this.getSize().height - fm.getHeight())/2;
      g.drawString(s, xstart, ystart);