-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInputVerifier.java
More file actions
67 lines (58 loc) · 2.28 KB
/
Copy pathInputVerifier.java
File metadata and controls
67 lines (58 loc) · 2.28 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
import javax.swing.*;
import java.awt.*;
public class InputVerifier {
// Declare instance variables for components used in the GUI
private JFrame main_frame;
private JLabel inputLabel;
private JTextField inputField;
private JButton verifyButton;
private JButton quitButton;
private JLabel resultLabel;
public InputVerifier() {
main_frame = new JFrame("Integer Input Verifier");
// Create components needed in GUI
inputLabel = new JLabel("Enter an integer:");
inputField = new JTextField(9);
verifyButton = new JButton("Verify");
quitButton = new JButton("Quit");
resultLabel = new JLabel("");
// Add components to the frame
JPanel panel = new JPanel();
panel.add(inputLabel);
panel.add(inputField);
panel.add(verifyButton);
panel.add(quitButton);
panel.add(resultLabel);
main_frame.add(panel);
// Set frame properties
main_frame.setSize(300, 120);
main_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main_frame.setLocationRelativeTo(null);
main_frame.setResizable(false);
main_frame.setVisible(true);
// Add action listeners to buttons. Lambda functionns so that when the button is pressed, it will call the function.
verifyButton.addActionListener(e -> checkInteger());
// Disposes of frame when button clicked
quitButton.addActionListener(e -> main_frame.dispose());
}
// Method that checks if the input is an integer when the verify button is clicked
public void checkInteger() {
String input = inputField.getText();
try {
// Parse input to integer
int value = Integer.parseInt(input);
// Display message if input is an integer
resultLabel.setText(input + " is an integer.");
inputField.setText("");
} catch (NumberFormatException ex) {
// Display message if input is not an integer
JOptionPane.showMessageDialog(main_frame, input + " is not an integer");
inputField.setText("");
resultLabel.setText("");
}
}
// Main method that runs the program
public static void main(String[] args) {
new InputVerifier();
}
}