gpt4 book ai didi

java - 只允许在 JTextField 中输入数字和符号 (-)

转载 作者:行者123 更新时间:2023-12-02 07:49:37 25 4
gpt4 key购买 nike

我正在尝试创建一个数学测验,我只希望用户能够输入数字,无论它们是负数还是正数。有什么办法可以做到吗?我曾考虑过使用正则表达式,但听说它们不好用。我尝试使用按键监听器,但是如果用户粘贴怎么办?我尝试解析字符串以获取整数,但负号将不起作用。

有什么想法吗?

package com.quiz.ui;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class SSCCE {

private JFrame frame;

private JPanel contentPane;

private JTextField usernameField;

public static void main(String[] arguments) {
new SSCCE().construct();
}

public void construct() {
frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getContentPane());
frame.pack();
frame.setVisible(true);
}

public JPanel getContentPane() {
usernameField = new JTextField(5);
usernameField.addKeyListener(new KeyListener() {

@Override
public void keyPressed(KeyEvent arg0) {
int keyCode = arg0.getKeyCode();
if ((keyCode > 47 && keyCode < 58) || keyCode == 45) {
arg0.consume();
}
System.out.println(arg0.getKeyCode());
}

@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub

}
});

contentPane = new JPanel(new BorderLayout());
contentPane.add(usernameField);

return contentPane;
}

}

最佳答案

使用DocumentFilter :

NumberOnlyFilter.java:

import javax.swing.*;
import javax.swing.text.*;
import java.util.regex.*;
public class NumberOnlyFilter extends DocumentFilter
{

public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
{
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.insert(offset, text);
if(!containsOnlyNumbers(sb.toString())) return;
fb.insertString(offset, text, attr);
}
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
{
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.replace(offset, offset + length, text);
if(!containsOnlyNumbers(sb.toString())) return;
fb.replace(offset, length, text, attr);
}

/**
* This method checks if a String contains only numbers
*/
public boolean containsOnlyNumbers(String text)
{
Pattern pattern = Pattern.compile("([+-]{0,1})?[\\d]*");
Matcher matcher = pattern.matcher(text);
boolean isMatch = matcher.matches();
return isMatch;
}

}

然后你可以像这样使用它:

((AbstractDocument)yourTxtField.getDocument()).setDocumentFilter(new NumberOnlyFilter());

关于java - 只允许在 JTextField 中输入数字和符号 (-),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8017811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com