Java Reference
In-Depth Information
29 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
30 frame.setSize(
new
Dimension(350, 100));
31 frame.setLayout(
new
FlowLayout());
32 frame.add(numberField);
33 frame.add(verifyButton);
34 frame.add(validLabel);
35 frame.setVisible(
true
);
36 }
37
38 // Returns whether the given string is a valid Visa
39 // card number according to the Luhn checksum algorithm.
40
public boolean
isValidCC(String text) {
41
int
sum = 0;
42
for
(
int
i = text.length() - 1; i >= 0; i--) {
43
int
digit = Integer.parseInt(
44 text.substring(i, i + 1));
45
if
(i % 2 == 0) { // double even digits
46 digit *= 2;
47 }
48 sum += (digit / 10) + (digit % 10);
49 }
50
51 // valid numbers add up to a multiple of 10
52
return
sum % 10 == 0 && text.startsWith("4");
53 }
54
55 // Sets label's text to show whether CC number is valid.
56
public void
actionPerformed(ActionEvent event) {
57 String text = numberField.getText();
58
if
(isValidCC(text)) {
59 validLabel.setText("Valid number!");
60 }
else
{
61 validLabel.setText("Invalid number.");
62 }
63 }
64 }
The GUIs we have developed so far use only a few components (buttons, text fields,
and labels) and can respond to only one kind of event (action events). In this section,
we'll look at some other useful components and events that GUI programs can use
and to which they can respond.
Search WWH ::
Custom Search