Also available as ButtonTextApplet.java

/**
 * A simple Applet (based on ButtonText2 stand-alone app).
 *  
 * Similar to ButtonText sample, but this one
 * puts the text field at top and not in BorderLayout.CENTER
 * so that it's size is preserved.
 *
 * This class also implements ActionListener, so we 
 * can use it to handle Action events
 *
 * The main creates a window with a bunch of buttons 
 * and a textfield.
 * Uses a JPanel to hold the buttons (container component).
 *
 * Whenever the user presses a button the button text is appended to
 * the textfield
 *
 * @author Dave Hollinger
 * @version 1.0
 */

import javax.swing.*;
import java.awt.*;       // needed for Container
import java.awt.event.*;  // needed for event types (listeners)

public class ButtonTextApplet extends JApplet implements ActionListener {

  // The textfield must not be anonymouse, since we want to        
  // be able to modify it from event handlers

  JTextField jt;

  public void init() {

        Container c = getContentPane();
        // set up layout manager
        c.setLayout(new BorderLayout(10,10));
        
        // add single text Area
        jt = new JTextField();
        jt.setSize(100,20);
        jt.setFont(new Font("Arial",Font.BOLD,16));
        jt.setBackground(Color.WHITE);
        jt.setForeground(Color.BLUE);
        c.add(jt,BorderLayout.NORTH);

        // add a button panel 
        c.add( createButtonPanel(), BorderLayout.CENTER );
        

        // establish what happens when the window is closed
        // (without this the program would keep running!)
        // NOT FOR APPLET        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // set the size
        setSize(200,200);
        // turn it on
        setVisible(true);
  }


  JPanel createButtonPanel() {
        // create a JPanel with a bunch of buttons in it arranged in
        // a grid.
        JPanel jp = new JPanel();

        // establish the layout manager
        // 2 rows, 3 cols everything 5 pixels apart
        jp.setLayout( new GridLayout(2,3,5,5));

        // add a bunch of buttons
        for (int i=0;i<6;i++) {
          JButton j = new JButton(new Integer(i).toString());
          // change the font
          j.setFont(new Font("Courier",Font.BOLD,20));

          // change the colors
          j.setBackground(Color.WHITE);
          j.setForeground(Color.BLACK);

          // set up the listener for this button
          // NOTE: We listen to ourself (we are an ActionListener!).
          j.addActionListener(this);

          // add the button to the panel
          jp.add(j);
        }
        return(jp);
  }

  // here is the method required as an ActionListener
  // (there is only one!)

  public void actionPerformed(ActionEvent e) {

        // find out what the action was
        // (for buttons, this is the button text by default)
        String act = e.getActionCommand();

        jt.setText(jt.getText() + act );
  }

}