Java Reference
In-Depth Information
Let's write a GUI that allows the user to type in a credit card number, press a but-
ton to verify the number, and receive a message stating whether the number was
valid. The GUI will have the following appearance:
To validate the credit card number, we'll place a listener on the Verify CC
Number button. The code for the listener's actionPerformed method will need
to read the text from the text field, decide whether the number is valid, and use
that information to set the text of the label. Since the listener involves interaction
between components, we'll make it object-oriented and make it act as its own
listener.
As usual, let's deal with components and layout first before we worry about
event handling. The frame can use a FlowLayout that wraps the text label to a sec-
ond line.
The initial version of the program does not respond to events. As with the previous
BmiGui3 example, we'll make the GUI act as its own client program by incorporat-
ing a main method. Here is the initial version of the program:
1 // Presents a GUI to verify credit card numbers.
2 // Initial version without event handling.
3
4 import java.awt.*;
5 import javax.swing.*;
6
7 public class CreditCardGUI1 {
8 public static void main(String[] args) {
9 CreditCardGUI1 gui = new CreditCardGUI1();
10 }
11
12 // fields
13 private JFrame frame;
14 private JTextField numberField;
15 private JLabel validLabel;
16 private JButton verifyButton;
17
18 // creates components, does layout, shows window onscreen
19 public CreditCardGUI1() {
20 numberField = new JTextField(16);
21 validLabel = new JLabel("not yet verified");
Search WWH ::




Custom Search