限制键入JTextField的字符数 [英] Limit the amount of characters typed into a JTextField

查看:63
本文介绍了限制键入JTextField的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这将是在网络上进行的简单搜索,但我无法弄清楚.到目前为止,这是我正在使用的东西.忽略eventHandler,我知道它为空.我想限制charField JTextField以便用户只能键入一个字符.我认为这很容易,因为所有应用程序都会限制您输入州或邮政编码时可以输入的数字量.

I figured this would be a simple search on the web but I can't figure this out. Here is what I'm working with so far. Ignore the eventHandler, I know its empty. I want to limit the charField JTextField so that the user can only type one character. I figured this would be easy because of all the apps that limit the amount of numbers you can type when entering State or Zipcode.

需要明确的是,我不是要验证输入,而是要限制输入.我希望它在输入一个字符后忽略击键.

To be clear, I'm not looking to validate input, I'm looking to limit input. I want it to ignore keystrokes after one character has been entered.

package Week6;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;

public class Index extends JPanel{

    private JLabel searchLabel;
    private JTextArea searchField;
    private JLabel charLabel;
    private JTextField charField;


public Index(){

    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.NORTH;
    setBackground(Color.WHITE);

    super.setLayout(gridbag);

    searchLabel = new JLabel("Enter text to be searched:");
    searchField = new JTextArea("", 5, 20);
    JScrollPane scroll = new JScrollPane(searchField);  

    searchField.setLineWrap(true);
    searchField.setWrapStyleWord(true);
    searchField.setOpaque(true);
    charLabel = new JLabel("Exter a character:");
    charField = new JTextField("", 5);      
    c.insets = new Insets(10, 10, 10, 10);

    c.gridx = 0;
    c.gridy = 0;    
    add(searchLabel, c);
    c.gridx = 1;
    c.gridy = 0;    
    add(scroll, c);
    c.gridx = 0;
    c.gridy = 1;
    add(charLabel, c);
    c.gridx = 1;
    c.gridy = 1;
    add(charField, c);  


    CharHandler charhandler = new CharHandler();
    charField.addActionListener(charhandler);   
    }

    class CharHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
        }
    }
}

推荐答案

为此,您应该使用DocumentFilter,看看

You should use a DocumentFilter for this, take a look at Implementing a Document Filter and DocumentFilter Examples

它允许您在将文本直接应用于基础Document之前将其过滤掉,这使其具有足够的灵活性,可以与从AbstractDocument扩展的任何Document实现一起使用,并考虑了用例用户在其中将文本粘贴到字段中或调用setText

It will allow you to filter out text coming directly before it's applied to the underlying Document, which makes it flexible enough to be used with any Document implementation that extends from AbstractDocument, takes into account the use cases where the user pastes text into the field or calls setText

例如...

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import javax.print.attribute.AttributeSet;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class FilterTest {

    public static void main(String[] args) {
        new FilterTest();
    }

    public FilterTest() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTextField field = new JTextField(10);
                ((AbstractDocument)field.getDocument()).setDocumentFilter(new SizeFilter(5));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(field);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class SizeFilter extends DocumentFilter {

        private int maxCharacters;

        public SizeFilter(int maxChars) {
            maxCharacters = maxChars;
        }

        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
                        throws BadLocationException {

            if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) {
                super.insertString(fb, offs, str, a);
            } else {
                Toolkit.getDefaultToolkit().beep();
            }
        }

        public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
                        throws BadLocationException {

            if ((fb.getDocument().getLength() + str.length()
                            - length) <= maxCharacters) {
                super.replace(fb, offs, length, str, a);
            } else {
                Toolkit.getDefaultToolkit().beep();
            }
        }
    }

}

这篇关于限制键入JTextField的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆