如何在Java中为showInputDialog中的输入添加限制

如何在Java中为showInputDialog中的输入添加限制,java,input,dialog,Java,Input,Dialog,我对Java非常陌生,我想增加一个限制,限制我的游戏玩家在获得前10名高分时,可以在JOptionPane.showInputDialog中输入多少个字符。我希望输入限制为5个字符。我对这段游戏的代码是: // checkTop10Highscore returns a position of the highscore in the top 10, or -1 if the score of the player // is not in the top 10

我对Java非常陌生,我想增加一个限制,限制我的游戏玩家在获得前10名高分时,可以在JOptionPane.showInputDialog中输入多少个字符。我希望输入限制为5个字符。我对这段游戏的代码是:

        // checkTop10Highscore returns a position of the highscore in the top 10, or -1 if the score of the player
        // is not in the top 10 highscores.
        // This is chosen instead of a boolean to prevent an extra database call after knowing it is in the top 10 to
        // know where it is in the top 10 - this is now done in one call.
        // playerCar.getScore() -- put in args below when finished testing
        int posInTop10 = PlayerHighscoreCheck.checkTop10Highscore(playerCar.getScore());

        if (posInTop10 == -1 && !this.renderedOnce) { // posInTop10 == -1 for testing dialog screen, != for normal gameplay
            JFrame frame = new JFrame("InputDialog PlayerName");

            // Prompt the player to enter their name
            String playerName = JOptionPane.showInputDialog
                    (frame, "Congratulations, your score is in the top 10! Enter your name here.");

            // Get the user's input. Note that if they press Cancel, 'name' will be null
            System.out.printf("The user's name is '%s'.\n", playerName);
            if (playerName == null) {
                playerName = "UNKWN";
            }
            // Save the input as playerName
            // Use the playerName in the database

            if(playerName.length() <= 5) {
                PlayerHighscoreCheck.savePlayerNameInTop10(playerName, playerCar.getScore(), posInTop10);
                renderedOnce = true;
                System.out.print("Saved name + score in database \n");
            } else {
                JFrame frameMaxChars = new JFrame("InputDialog PlayerName");

                // Prompt the player to enter their name
                String playerNameMax5Chars = JOptionPane.showInputDialog
                        (frame, "Your name can be a maximum of 5 characters");

                System.out.printf("The user's name is '%s'.\n", playerNameMax5Chars);
                // String playerName = JOptionPane.showInputDialog(frame, "Your name can be a maximum of 5 characters!");
                // System.out.print("Your name can be a maximum of 5 characters");

                if (playerNameMax5Chars.length() <= 5) {
                    PlayerHighscoreCheck.savePlayerNameInTop10(playerNameMax5Chars, playerCar.getScore(), posInTop10);
                    renderedOnce = true;
                    System.out.print("Saved name + score in database \n");
                }
            }
        }
//checkTop10Highscore返回最高分在前10名中的位置,或者如果玩家的分数为-1
//不在前十名的高分中。
//选择此选项而不是布尔值,以防止在知道它位于前10名之后进行额外的数据库调用
//知道它在前10名中的位置-现在只需一次通话即可完成。
//playerCar.getScore()--完成测试后,在下面输入参数
int posInTop10=PlayerHighscoreCheck.checkTop10Highscore(playerCar.getScore());
如果(posInTop10==-1&&!this.renderondance){//posInTop10==-1用于测试对话框屏幕,!=用于正常游戏
JFrame frame=新JFrame(“InputDialog PlayerName”);
//提示玩家输入他们的名字
String playerName=JOptionPane.showInputDialog
(框架:“祝贺你,你的分数在前10名!在这里输入你的名字。”);
//获取用户的输入。请注意,如果他们按“取消”,则“名称”将为空
System.out.printf(“用户名是“%s”。\n”,playerName);
if(playerName==null){
playerName=“unknwn”;
}
//将输入另存为playerName
//在数据库中使用playerName

如果(playerName.length()JOptionPane的输入字段不提供该功能,但您可以为其提供自己的JTextField,您必须事先配置该字段,以便只允许使用五个字符

JOptionPane的消息不必是字符串。例如,它可以是AWT或Swing组件,在这种情况下,组件本身显示为消息。还允许使用数组,数组本身可以包含字符串和/或组件。您可以利用它来传递自己的输入字段,而不是默认字段

您希望调用的不是showInputDialog,它不会显示内部创建的输入字段,而是您自己的自定义消息,其中包含自定义的JTextField

对于仅允许五个字符的自定义,您必须在其上创建自定义和。自定义文档筛选器必须覆盖
insertString
replace
方法以限制文档的总长度

把所有这些放在一起看起来像这样:

int maxLength = 5;

JTextField nameField = new JTextField(maxLength);

PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
    @Override
    public void insertString(FilterBypass bypass,
                             int offset,
                             String text,
                             AttributeSet attr)
    throws BadLocationException {
        int newLength =
            bypass.getDocument().getLength() + text.length();
        if (newLength <= maxLength) {
            super.insertString(bypass, offset, text, attr);
        }
    }

    @Override
    public void replace(FilterBypass bypass,
                        int offset,
                        int length,
                        String text,
                        AttributeSet attr)
    throws BadLocationException {
        int newLength =
            bypass.getDocument().getLength() - length + text.length();
        if (newLength <= maxLength) {
            super.replace(bypass, offset, length, text, attr);
        }
    }
});
nameField.setDocument(doc);

int response = JOptionPane.showOptionDialog(frame, new Object[] {
        "Congratulations, your score is in the top 10! Enter your name here.",
        nameField
    },
    "High Scorer",
    JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null, null, null);

String playerName =
    (response == JOptionPane.OK_OPTION ? nameField.getText() : null);
int maxLength=5;
JTextField nameField=新的JTextField(maxLength);
PlainDocument文档=新的PlainDocument();
doc.setDocumentFilter(新的DocumentFilter(){
@凌驾
public void insertString(过滤器旁路,
整数偏移,
字符串文本,
属性集属性(attr)
抛出BadLocationException{
int newLength=
绕过.getDocument().getLength()+文本.length();

如果(newLengthJOptionPane的输入字段不提供该功能,但您可以为其提供自己的JTextField,您必须事先配置该字段,以便只允许使用五个字符

JOptionPane的消息不必是字符串。例如,它可以是AWT或Swing组件,在这种情况下,组件本身显示为消息。还允许使用数组,数组本身可以包含字符串和/或组件。您可以利用它来传递自己的输入字段,而不是默认字段

您希望调用的不是showInputDialog,它不会显示内部创建的输入字段,而是您自己的自定义消息,其中包含自定义的JTextField

对于仅允许五个字符的自定义,您必须在其上创建自定义和。自定义文档筛选器必须覆盖
insertString
replace
方法以限制文档的总长度

把所有这些放在一起看起来像这样:

int maxLength = 5;

JTextField nameField = new JTextField(maxLength);

PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
    @Override
    public void insertString(FilterBypass bypass,
                             int offset,
                             String text,
                             AttributeSet attr)
    throws BadLocationException {
        int newLength =
            bypass.getDocument().getLength() + text.length();
        if (newLength <= maxLength) {
            super.insertString(bypass, offset, text, attr);
        }
    }

    @Override
    public void replace(FilterBypass bypass,
                        int offset,
                        int length,
                        String text,
                        AttributeSet attr)
    throws BadLocationException {
        int newLength =
            bypass.getDocument().getLength() - length + text.length();
        if (newLength <= maxLength) {
            super.replace(bypass, offset, length, text, attr);
        }
    }
});
nameField.setDocument(doc);

int response = JOptionPane.showOptionDialog(frame, new Object[] {
        "Congratulations, your score is in the top 10! Enter your name here.",
        nameField
    },
    "High Scorer",
    JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null, null, null);

String playerName =
    (response == JOptionPane.OK_OPTION ? nameField.getText() : null);
int maxLength=5;
JTextField nameField=新的JTextField(maxLength);
PlainDocument文档=新的PlainDocument();
doc.setDocumentFilter(新的DocumentFilter(){
@凌驾
public void insertString(过滤器旁路,
整数偏移,
字符串文本,
属性集属性(attr)
抛出BadLocationException{
int newLength=
绕过.getDocument().getLength()+文本.length();
如果(新长度)