限制键入JTextField的字符数

时间:2014-08-20 23:18:20

标签: java swing validation input jtextfield

我认为这将是一个简单的网络搜索,但我无法弄清楚这一点。这是我到目前为止所做的工作。忽略eventHandler,我知道它是空的。我想限制charField JTextField,以便用户只能键入一个字符。我认为这很容易,因为所有应用程序限制了您在输入State或Zipcode时可以输入的数字量。

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

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){
        }
    }
}

1 个答案:

答案 0 :(得分:4)

您应该使用DocumentFilter来查看Implementing a Document FilterDocumentFilter Examples

它允许您在将文本应用于基础Document之前过滤掉直接发送的文本,这使其足够灵活,可以与Document扩展的AbstractDocument实现一起使用1}},考虑用户将文字粘贴到字段或调用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();
            }
        }
    }

}