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