JTextField 设置输入限制 [英] JTextField set input limit

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

问题描述

您好,我正在尝试使用 setDocument 方法来限制用户可以在文本字段中输入的字符数.但不知何故,它并没有限制输入字符的数量.这是代码

Hi I am trying to use setDocument method to limit the number of characters a user can input in the text field. But somehow it does not limit the no of input characters. Here's the code

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;


public class JTextFieldCharLimit extends PlainDocument {


    private int limit;

    public JTextFieldCharLimit(int limit)
    {
        super();
        this.limit = limit;
    }
    public void inserString(int offset, String str, AttributeSet set) throws BadLocationException
    {
        if(str == null)
        {
            return;
        } else if((getLength() + str.length()) <= limit)
        {
            str = str.toUpperCase();
            super.insertString(offset, str, set);
        }
    }




}

我在另一个类中使用这个类,我在其中声明了我的文本字段,如下所示:

I am using this class in another class where I have declared my text field as follows:

void playerInfoScreen(JFrame mainFrame, JPanel menuPanel)
    {
        final ScreenConstructor playerName = new ScreenConstructor();
        final JFrame frame = mainFrame;
        final JPanel returnPanel = menuPanel;

        final JPanel panel = playerName.createPanel("menu panel");

        final JButton returnButton = playerName.createButton("MAIN MENU");
        final JTextField textEntry = playerName.createTextField(10);
                // text field length needs to be set to prevent long texts
        final JLabel label = playerName.createLabel("Enter Player Name:");

        playerName.addButtonToPanel(panel, returnButton);
        playerName.addLabelToPanel(panel, label);
        playerName.addJTextFieldToPanel(panel, textEntry);

        textEntry.setDocument(new JTextFieldCharLimit(5));
        playerName.displayScreen(frame, panel);
            // check for esc button to let user return back to main menu




        textEntry.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String player = textEntry.getText(); // save entered player name
                storedPlayerName = player; // store player in order to use it in highscores and display on game screen
                GameScreen game = new GameScreen(frame, panel); // go to game screen 
            }
        });


        returnButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                frame.setContentPane(returnPanel); // go back to previous panel
            }
        });




    }

推荐答案

使用 DocumentFilter.请参阅实施文档过滤器DocumentFilter 示例 了解更多详情.

Use a DocumentFilter. See Implementing a Document Filter and DocumentFilter Examples for more details.

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

归功于 MDP

((AbstractDocument)textEntry.getDocument()).setDocumentFilter(new SizeFilter(5));

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

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