-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNonEditableCounter.java
More file actions
58 lines (48 loc) · 2.02 KB
/
NonEditableCounter.java
File metadata and controls
58 lines (48 loc) · 2.02 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
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class NonEditableCounter {
JFrame frame = new JFrame();
JButton count, reset;
JTextField textField = new JTextField("0",10); // default text inside the field is '0'
NonEditableCounter() {
frame.setName("Count_Reset");
frame.setSize(400,150);
frame.setLayout(new FlowLayout()); //otherwise, multiple components wouldn't be visible
// buttons
count = new JButton("count"); // will increase value each time it's pressed
reset = new JButton("reset"); // set everything to 0
// when false, user cannot edit / insert any sort of values inside the text field
textField.setEditable(false);
// adding components to the JFrame
frame.add(count);
frame.add(textField);
frame.add(reset);
// to perform action using buttons
count.addActionListener(new Inner()); // pressing the count button will increase the text field value by 1
reset.addActionListener(new Inner()); // pressing the reset button will set the text field to '0'
frame.setVisible(true); // only way to make the frame visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class Inner implements ActionListener {
@Override
public void actionPerformed(ActionEvent actionEvent)
{
//detecting which button is pressed
if(actionEvent.getSource() == count) {
int textInt = Integer.parseInt(textField.getText());
textField.setText((textInt + 1) + "");
}
// warning : pressing the reset button will set the text field to '0'
else if(actionEvent.getSource() == reset){
textField.setText("0");
}
}
}
// main method
public static void main(String[] args) {
// just creating an object to use that constructor
new NonEditableCounter();
}
}