Source of LabelDemo.java


  1: 
  2: import javax.swing.*;
  3: import java.awt.*;
  4: import java.awt.event.*;
  5: 
  6: /**
  7:  Class to demonstrate placing a label on a text field.
  8: */
  9: public class LabelDemo extends JFrame implements ActionListener
 10: {
 11:     public static final int WIDTH = 300;
 12:     public static final int HEIGHT = 200;
 13: 
 14:     private JTextField name;
 15: 
 16:     public LabelDemo( )
 17:     {
 18:         setTitle("Name Tester");
 19:         setSize(WIDTH, HEIGHT);
 20:         addWindowListener(new WindowDestroyer( ));
 21:         Container content = getContentPane( );
 22:         content.setLayout(new GridLayout(2, 1));
 23: 
 24:         JPanel namePanel = new JPanel( );
 25:         namePanel.setLayout(new BorderLayout( ));
 26:         namePanel.setBackground(Color.LIGHT_GRAY);
 27: 
 28:         name = new JTextField(20);
 29:         namePanel.add(name, BorderLayout.SOUTH);
 30:         JLabel nameLabel = new JLabel("Enter your name here:");
 31:         namePanel.add(nameLabel, BorderLayout.CENTER);
 32: 
 33:         content.add(namePanel);
 34: 
 35:         JPanel buttonPanel = new JPanel( );
 36:         buttonPanel.setLayout(new FlowLayout( ));
 37:         JButton b = new JButton("Test");
 38:         b.addActionListener(this);
 39:         buttonPanel.add(b);
 40:         b = new JButton("Clear");
 41:         b.addActionListener(this);
 42:         buttonPanel.add(b);
 43: 
 44:         content.add(buttonPanel);
 45:     }
 46: 
 47:     public void actionPerformed(ActionEvent e)
 48:     {
 49:         if (e.getActionCommand( ).equals("Test"))
 50:             name.setText("A very good name!");
 51:         else if (e.getActionCommand( ).equals("Clear"))
 52:             name.setText("");
 53:         else
 54:             name.setText("Error in window interface.");
 55:     }
 56: 
 57: 
 58:     public static void main(String[] args)
 59:     {
 60:         LabelDemo w = new LabelDemo( );
 61:         w.setVisible(true);
 62:     }
 63: 
 64: 
 65: }