如何允许在jTextField中仅引入数字?

2022-09-05 00:30:25

我试图使用这里显示的示例,但java显示错误消息

“无法将属性集解析为类型”

这就是为什么我试图使用另一种只允许数字的方法:

txtUsername.addKeyListener(new MyKeyListener());

public class MyKeyListener extends KeyAdapter{
  public void keyPressed(KeyEvent ke){
      System.out.println("Key pressed code = "+ke.getKeyCode());
      if (ke.getKeyCode()>=48 && ke.getKeyCode()<=57)
              return true;
      else
              return false;
  }
} 

但是,它当然不起作用,因为方法是.那么,为了在文本字段中仅打印数字,该怎么办?keyPressedvoid


答案 1

在这里检查这个代码片段,这就是你只允许JTextField中的数字,通过使用DocumentFilter,作为最有效的方式:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class InputInteger
{
    private JTextField tField;
    private MyDocumentFilter documentFilter;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Input Integer Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        tField = new JTextField(10);
        ((AbstractDocument)tField.getDocument()).setDocumentFilter(
                new MyDocumentFilter());        
        contentPane.add(tField); 

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                new InputInteger().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

class MyDocumentFilter extends DocumentFilter
{   
    @Override
    public void insertString(DocumentFilter.FilterBypass fp
            , int offset, String string, AttributeSet aset)
                                throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger)
            super.insertString(fp, offset, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fp, int offset
                    , int length, String string, AttributeSet aset)
                                        throws BadLocationException
    {
        int len = string.length();
        boolean isValidInteger = true;

        for (int i = 0; i < len; i++)
        {
            if (!Character.isDigit(string.charAt(i)))
            {
                isValidInteger = false;
                break;
            }
        }
        if (isValidInteger)
            super.replace(fp, offset, length, string, aset);
        else
            Toolkit.getDefaultToolkit().beep();
    }
}

或者可以简单地使用这种方法,正如@Carlos Heuberger所给出的那样。

@Override
public void insertString(FilterBypass fb, int off
                    , String str, AttributeSet attr) 
                            throws BadLocationException 
{
    // remove non-digits
    fb.insertString(off, str.replaceAll("\\D++", ""), attr);
} 
@Override
public void replace(FilterBypass fb, int off
        , int len, String str, AttributeSet attr) 
                        throws BadLocationException 
{
    // remove non-digits
    fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
}

答案 2

我建议使用JFormattedTextField,这是如何:如何使用格式化文本字段