-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKeyPad.java
More file actions
106 lines (87 loc) · 2.57 KB
/
Copy pathKeyPad.java
File metadata and controls
106 lines (87 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package ch24;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* A component that lets the user enter a number, using a button pad labeled
* with digits.
*/
public class KeyPad extends JPanel {
private JPanel buttonPanel;
private JButton clearButton;
private JTextField display;
/**
* Constructs the keypad panel.
*/
public KeyPad() {
setLayout(new BorderLayout());
// Add display field
display = new JTextField();
add(display, "North");
// Make button panel
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 3));
// Add digit buttons
addButton("7");
addButton("8");
addButton("9");
addButton("4");
addButton("5");
addButton("6");
addButton("1");
addButton("2");
addButton("3");
addButton("0");
addButton(".");
// Add clear entry button
clearButton = new JButton("CE");
buttonPanel.add(clearButton);
class ClearButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
display.setText("");
}
}
ActionListener listener = new ClearButtonListener();
clearButton.addActionListener(new ClearButtonListener());
add(buttonPanel, "Center");
}
/**
* Adds a button to the button panel.
*
* @param label the button label
*/
private void addButton(final String label) {
class DigitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// Don't add two decimal points
if (label.equals(".") && display.getText().indexOf(".") != -1) {
return;
}
// Append label text to button
display.setText(display.getText() + label);
}
}
JButton button = new JButton(label);
buttonPanel.add(button);
ActionListener listener = new DigitButtonListener();
button.addActionListener(listener);
}
/**
* Gets the value that the user entered.
*
* @return the value in the text field of the keypad
*/
public double getValue() {
return Double.parseDouble(display.getText());
}
/**
* Clears the dislay.
*/
public void clear() {
display.setText("");
}
}