  1 //gt2.java  -- get text in TextField, by tsaiwn@cs.nctu.edu.tw
  2 //javac gt2.java
  3 //java gt2
  4 import java.awt.*;
  5 import java.awt.event.*;
  6 class gt2 {
  7    Frame f; Button ba, bb, bc;
  8    TextField t;
  9    public static void main(String xx[ ]) {
 10      new gt2( );
 11    }
 12    gt2( ) {
 13       init( );
 14       start( );
 15    }
 16    void init( ) {
 17      f = new Frame("Ha ha");
 18      f.setSize(300,200);
 19      t = new TextField(20);
 20      ba = new Button("type chars in textfield then press right button");
 21      Panel p = new Panel( );
 22       p.add(new Button("type ID: ") );
 23       p.add(t);
 24      f.add(p, "North");
 25      f.add(ba, "South");
 26      bb = new Button("Press Me");
 27      f.add(bb, "East");
 28      f.setVisible(true);
 29    }
 30    void start( ) {
 31      YLAU ar3 = new YLAU(f, ba, bb, t);
 32      bb.addActionListener(ar3);
 33      t.addActionListener(ar3);
 34      t.addKeyListener(ar3);
 35      t.setBackground(Color.yellow);
 36      bb.addActionListener(ar3);
 37      t.requestFocus( );  // direct the cursor to this TextField
 38    }
 39 } // class gt2
 40 class YLAU implements ActionListener, KeyListener {
 41    Frame f; Button ba, bb;
 42    TextField t;
 43    YLAU(Frame f, Button b, Button bb, TextField tfd) {
 44      this.f = f; 
 45      this.ba = b;  this.bb = bb;
 46      t = tfd;
 47    }
 48    public void actionPerformed(ActionEvent e) {
 49       if(e.getSource( ) == bb) {
 50          ba.setBackground(Color.green);
 51          String ggyy = t.getText( );
 52          ba.setLabel( ggyy );
 53          if(ggyy.equals("exit")) System.exit(0);
 54       }
 55       if( e.getSource( ) == t ) {
 56          String ggyy = t.getText( );
 57          ba.setLabel( ggyy );
 58          ba.setBackground(Color.red);
 59       }
 60    }  //actionPerformed
 61    /// /// // KeyListener
 62    public void keyPressed(KeyEvent e) {
 63       ba.setBackground(Color.blue);
 64    }
 65    public void keyReleased(KeyEvent e) {  } // donothing
 66    public void keyTyped(KeyEvent e) {
 67       ba.setBackground(Color.yellow);
 68       String ggyy = t.getText( );
 69       ba.setLabel( ggyy );
 70    }
 71  /// /// //
 72 }
