限制PLAIN_MESSAGE JOptionPane中输入文本的大小

时间:2018-05-08 15:06:28

标签: java swing joptionpane

我正在使用JOptionPane.showInputDialog()方法创建一个带有JOptionPane.PLAIN_MESSAGE选项类型的对话框。这将显示带有自由文本输入字段的确认弹出窗口。我需要文本最多256个字符,但在声明对话框时找不到任何限制它的选项。

目前我测试返回String的长度,如果它太长则截断它:

private void showConfirmationPopup(Component parent) {
    String title = "";
    String message = "";
    String defaultComment = "";
    // Open an Input Dialog with a Text field
    Object comment = JOptionPane.showInputDialog(
            parent,
            message, 
            title, 
            JOptionPane.PLAIN_MESSAGE,
            null,
            null,
            defaultComment);

    if(comment != null) {
        String inputComment = (String)comment;
        if(inputComment.length()>256) {
            inputComment = inputComment.substring(0, 256);
        }
        // ...
    }
}

我想知道在声明对话框时是否可以设置限制,或者是否有一个聪明的技巧来实现它,所以我不必在事后进行检查。

1 个答案:

答案 0 :(得分:1)

阅读Stopping Automatic Dialog Closing上的Swing教程中的部分。

它显示了如何编辑输入的文本,并防止在未输入有效数据时关闭对话框。

编辑:

您可以尝试访问选项窗格的文本字段:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class OptionPaneInput2
{
    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );

        JTextField label = new JTextField("How old are you?");
        label.addAncestorListener( new AncestorListener()
        {
            @Override
            public void ancestorAdded(AncestorEvent e)
            {
                Component component = e.getComponent();
                Container parent = component.getParent();
                JTextField textField = (JTextField)parent.getComponent(1);
                System.out.println("added");
            }

            @Override
            public void ancestorMoved(AncestorEvent e) {}

            @Override
            public void ancestorRemoved(AncestorEvent e) {}

        });


        //  Simple text field for input:

        String age = JOptionPane.showInputDialog(
            frame,
            label);

        frame.dispose();
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater( () -> createAndShowGUI() );
/*
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
*/
    }
}

通过将消息指定为JLabel,可以在标签添加到对话框时收到通知,然后您可以访问输入文本字段并将DocumentFilter添加到文本字段的Document并执行所需的编辑。

请参阅Implementing a DocumentFilter上的Swing教程,了解限制显示字符数的过滤器。

如果这对您来说仍然太有创意,那么我建议您只创建自己的自定义JDialog。这确实是最好的方法。

相关问题