【问题标题】:JTextField - how to determine which values can be typedJTextField - 如何确定可以输入哪些值
【发布时间】:2015-03-27 13:50:12
【问题描述】:

我正在开发一些计算器,所以上面的JTextField只能有一些字符。
实现这一目标的最佳方法是什么?

假设我有这个char[] values = 0,1,2,3,4,5,6,7,8,9,+,-,*,/,(,),.,,这些是用户可以输入的值。

【问题讨论】:

    标签: java swing jtextfield


    【解决方案1】:

    使用JFormattedTextField。您可以将MaskFormattersetValidCharacters(...) 方法一起使用,并指定一个包含有效字符的字符串。

    阅读 Using a MaskFormatter 上的 Swing 教程部分了解更多信息。

    或者另一种方法是使用带有DocumentFilter 的JTextField。阅读Implementing a DocumentFilter 上的 Swing 教程了解更多信息。

    【讨论】:

    • @RoeyGolzarpoor,您可以在论坛或网络上搜索使用该方法的代码。我相信你会找到一个例子。
    【解决方案2】:

    已经有几个像你这样的问题已经解决了:

    Filter the user's keyboard input into JTextField (swing)

    No blanks in JTextField

    根据这些,您应该使用 DocumentFilter 或 JFormattedTextField。

    【讨论】:

    • 我找不到使用char[] 作为有效输入的示例
    • 好吧,如果您选择使用 DocumentFilter,您可以验证用户输入的每个字符是否包含在您的 char 数组中。
    • 试着看看这个关于如何使用它的一个很好的例子:stackoverflow.com/questions/24844559/…
    【解决方案3】:

    最终我设法创建了自己的JTextField,它的实现方式如下:

    public class MyTextField extends JTextField {
    
        //final value for maximum characters
        private final int MAX_CHARS = 20;
    
        /**
         * A regex value which helps us to validate which values the user can enter in the input
         */
        private final String REGEX = "^[\\d\\+\\/\\*\\.\\- \\(\\)]*$";
    
        public MyTextField(){
    
            //getting our text as a document
            AbstractDocument document = (AbstractDocument) this.getDocument();        
    
            /**
             * setting a DocumentFilter which helps us to have only the characters we need
             */
            document.setDocumentFilter(new DocumentFilter() {
                public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
    
                    String text = fb.getDocument().getText(0, fb.getDocument().getLength());
                    text += str;
    
                    if ((fb.getDocument().getLength() + str.length() - length) <= MAX_CHARS && text.matches(REGEX)){
                        super.replace(fb, offs, length, str, a);
                    } 
                }
    
                public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
    
                    String text = fb.getDocument().getText(0, fb.getDocument().getLength());
                    text += str;
    
                    if ((fb.getDocument().getLength() + str.length()) <= MAX_CHARS && text.matches(REGEX)){
                        super.insertString(fb, offs, str, a);
                    }
                }
            });
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-14
      • 2010-11-02
      • 2019-10-02
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      相关资源
      最近更新 更多