-
Notifications
You must be signed in to change notification settings - Fork 0
/
JNumberField.java
54 lines (43 loc) · 1.37 KB
/
JNumberField.java
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
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.event.KeyEvent;
import static com.sun.java.accessibility.util.AWTEventMonitor.addKeyListener;
public final class JNumberField extends JTextField {
private int maxChar = -1;
public JNumberField(){
super();
addKeyListener(new java.awt.event.KeyAdapter(){
@Override
public void keyTyped(java.awt.event.KeyEvent evt){
jTextFieldKeyTyped(evt);
}
});
}
public void setMaxChar(int n){
this.maxChar = n;
}
public int getMaxChar(){
return this.maxChar;
}
public JNumberField(int max){
super();
this.setMaxChar(max);
addKeyListener(new java.awt.event.KeyAdapter(){
@Override
public void keyTyped(java.awt.event.KeyEvent evt){
jTextFieldKeyTyped(evt);
}
});
}
private void jTextFieldKeyTyped(KeyEvent evt) {
String operationChar = "0123456789.-";
if(!operationChar.contains(evt.getKeyChar()+"")){
evt.consume();
}
if((getText().length() >= this.getMaxChar() && (this.getMaxChar() != -1))){
evt.consume();
setText(getText().substring(0, this.getMaxChar()));
}
}
}