java jtextfield不能输入_Java 将JTextField输入限制为整数

小编典典

请勿为此使用KeyListener,因为你会错过很多内容,包括粘贴文本。同样,KeyListener是一个非常低级的构造,因此在Swing应用程序中应避免使用它。

SO上已经多次描述了该解决方案:使用DocumentFilter。这个站点上有几个示例,其中一些是我写的。

例如:using-documentfilter-filterbypass

同样对于教程帮助,请查看:实现DocumentFilter。

编辑

例如:

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.text.AttributeSet;

import javax.swing.text.BadLocationException;

import javax.swing.text.Document;

import javax.swing.text.DocumentFilter;

import javax.swing.text.PlainDocument;

public class DocFilter {

public static void main(String[] args) {

JTextField textField = new JTextField(10);

JPanel panel = new JPanel();

panel.add(textField);

PlainDocument doc = (PlainDocument) textField.getDocument();

doc.setDocumentFilter(new MyIntFilter());

JOptionPane.showMessageDialog(null, panel);

}

}

class MyIntFilter extends DocumentFilter {

@Override

public void insertString(FilterBypass fb, int offset, String string,

AttributeSet attr) throws BadLocationException {

Document doc = fb.getDocument();

StringBuilder sb = new StringBuilder();

sb.append(doc.getText(0, doc.getLength()));

sb.insert(offset, string);

if (test(sb.toString())) {

super.insertString(fb, offset, string, attr);

} else {

// warn the user and don't allow the insert

}

}

private boolean test(String text) {

try {

Integer.parseInt(text);

return true;

} catch (NumberFormatException e) {

return false;

}

}

@Override

public void replace(FilterBypass fb, int offset, int length, String text,

AttributeSet attrs) throws BadLocationException {

Document doc = fb.getDocument();

StringBuilder sb = new StringBuilder();

sb.append(doc.getText(0, doc.getLength()));

sb.replace(offset, offset + length, text);

if (test(sb.toString())) {

super.replace(fb, offset, length, text, attrs);

} else {

// warn the user and don't allow the insert

}

}

@Override

public void remove(FilterBypass fb, int offset, int length)

throws BadLocationException {

Document doc = fb.getDocument();

StringBuilder sb = new StringBuilder();

sb.append(doc.getText(0, doc.getLength()));

sb.delete(offset, offset + length);

if (test(sb.toString())) {

super.remove(fb, offset, length);

} else {

// warn the user and don't allow the insert

}

}

}

为什么这很重要?

如果用户使用复制和粘贴将数据插入文本组件怎么办?KeyListener可以错过吗?

你似乎希望检查数据是否可以表示int。如果他们输入了不合适的数字数据怎么办?

如果要允许用户以后输入重复数据怎么办?用科学计数法?

2020-03-01

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值