Java Reference
In-Depth Information
Next, we need to write the actionPerformed method. The method is short and
simple, because the isValidCC method does the bulk of the work:
// Sets label's text to show whether CC number is valid.
public void actionPerformed(ActionEvent event) {
String text = numberField.getText();
if (isValidCC(text)) {
validLabel.setText("Valid number!");
} else {
validLabel.setText("Invalid number.");
}
}
Here is the complete version of the program, which includes all the components
we just developed:
1 // Presents a GUI to verify credit card numbers.
2 // Final version with event handling.
3
4 import java.awt.*;
5 import java.awt.event.*;
6 import javax.swing.*;
7
8 public class CreditCardGUI2 implements ActionListener {
9 public static void main(String[] args) {
10 CreditCardGUI2 gui = new CreditCardGUI2();
11 }
12
13 // fields
14 private JFrame frame;
15 private JTextField numberField;
16 private JLabel validLabel;
17 private JButton verifyButton;
18
19 // creates components, does layout, shows window onscreen
20 public CreditCardGUI2() {
21 numberField = new JTextField(16);
22 validLabel = new JLabel("not yet verified");
23 verifyButton = new JButton("Verify CC Number");
24
25 // event listeners
26 verifyButton.addActionListener( this );
27
28 frame = new JFrame("Credit card number verifier");
Search WWH ::




Custom Search