Java Reference
In-Depth Information
Display 17.17
A Text Field (part 2 of 3)
17
public static final int NUMBER_OF_CHAR = 30;
18
private JTextField name;
19 public static void main(String[] args)
20 {
21 TextFieldDemo gui = new TextFieldDemo();
22 gui.setVisible( true );
23 }
24 public TextFieldDemo()
25 {
26 super ("Text Field Demo");
27 setSize(WIDTH, HEIGHT);
28 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
29 setLayout( new GridLayout(2, 1));
30 JPanel namePanel = new JPanel();
31 namePanel.setLayout( new BorderLayout());
32 namePanel.setBackground(Color.WHITE);
33 name = new JTextField(NUMBER_OF_CHAR);
34 namePanel.add(name, BorderLayout.SOUTH);
35 JLabel nameLabel = new JLabel("Enter your name here:");
36 namePanel.add(nameLabel, BorderLayout.CENTER);
37 add(namePanel);
38 JPanel buttonPanel = new JPanel();
39 buttonPanel.setLayout( new FlowLayout());
40 buttonPanel.setBackground(Color.BLUE);
41 JButton actionButton = new JButton("Click me");
42 actionButton.addActionListener( this );
43 buttonPanel.add(actionButton);
44 JButton clearButton = new JButton("Clear");
45 clearButton.addActionListener( this );
46 buttonPanel.add(clearButton);
47 add(buttonPanel);
48 }
49 public void actionPerformed(ActionEvent e)
50 {
51 String actionCommand = e.getActionCommand();
52 if (actionCommand.equals("Click me"))
53 name.setText("Hello " + name.getText());
54 else if (actionCommand.equals("Clear"))
55 name.setText("");
56 else
57 name.setText("Unexpected error.");
58 }
59 }
This sets the text field equal to the
empty string, which makes it blank.
(continued)
Search WWH ::




Custom Search