Limit the amount of characters typed into a JTextField [duplicate]

别等时光非礼了梦想. 提交于 2021-01-28 15:26:36

问题


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

回答1:


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

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

For example...

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();
            }
        }
    }

}


来源:https://stackoverflow.com/questions/25416006/limit-the-amount-of-characters-typed-into-a-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!