怎样让java文本框只输入数字问题
发布网友
发布时间:2022-04-30 18:53
我来回答
共1个回答
热心网友
时间:2022-04-13 06:44
java swing中利用JFormattedTextField的控件加keyReleased能实现,以下实现的只能输入数字的文本框代码:
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
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author Administrator
*/
public class JFormattedText extends JFrame {
private JFormattedTextField text;
public JFormattedText() {
JPanel panel = new JPanel();
text = new JFormattedTextField(new java.text.DecimalFormat("#0"));
// text = new JFormattedTextField();
// text.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
text.setFont(new java.awt.Font("宋体", 0, 12)); // NOI18N
text.setMaximumSize(new java.awt.Dimension(50, 21));
text.setMinimumSize(new java.awt.Dimension(50, 21));
text.setPreferredSize(new java.awt.Dimension(50, 21));
//过滤输入的字符
text.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
String old = text.getText();
JFormattedTextField.AbstractFormatter formatter = text.getFormatter();
if (!old.equals("")) {
if (formatter != null) {
String str = text.getText();
try {
long page = (Long) formatter.stringToValue(str);
text.setText(page + "");
} catch (ParseException pe) {
text.setText("1");//解析异常直接将文本框中值设置为1
}
}
}
}
});
panel.add(text);
this.add(panel);
this.setBounds(200, 100, 100, 100);
}
public static void main(String[] arg) {
new JFormattedText().setVisible(true);
}
}