java一个数字一个数字_在java中只接受一个数字

对于这类问题,个人而言,我会使用

DocumentFilter

它允许您限制进入字段的字符类型以及字符数.

public class RestrictInput {

public static void main(String[] args) {

new RestrictInput();

}

public RestrictInput() {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException ex) {

} catch (InstantiationException ex) {

} catch (IllegalAccessException ex) {

} catch (UnsupportedLookAndFeelException ex) {

}

JTextField field = new JTextField(2);

field.setHorizontalAlignment(JTextField.RIGHT);

((AbstractDocument) field.getDocument()).setDocumentFilter(new RestrictFilter());

JPanel panel = new JPanel(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();

gbc.gridx = 0;

gbc.gridy = 0;

panel.add(new JLabel("Please enter a integer:"), gbc);

gbc.gridx++;

gbc.anchor = GridBagConstraints.WEST;

gbc.weightx = 1;

panel.add(field, gbc);

int result = JOptionPane.showConfirmDialog(null, panel, "Input", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

if (result == JOptionPane.OK_OPTION) {

System.out.println("Use entered " + field.getText());

}

}

});

}

public class RestrictFilter extends DocumentFilter {

public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {

String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());

if (currentText.startsWith("-") || text.equals("-") || fb.getDocument().getLength() < 1) {

String value = text.substring(0, 1);

if (value.equals("-")) {

if (currentText.startsWith("-")) {

super.remove(fb, 0, 1);

} else {

super.insertString(fb, 0, value, attr);

}

} else if (fb.getDocument().getLength() < 2 && (value.equals("-") || Character.isDigit(value.charAt(0)))) {

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

}

}

}

public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {

if (length > 0) {

fb.remove(offset, length);

}

insertString(fb, offset, string, attr);

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值