gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:16:31 25 4
gpt4 key购买 nike

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

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

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);
}
// ...
}
}

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

最佳答案

阅读 Swing 教程中关于 Stopping Automatic Dialog Closing 的部分.

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

编辑:

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

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,您可以在标签添加到对话框时收到通知,然后您可以访问输入文本字段并添加 DocumentFilterDocument文本字段并执行所需的编辑。

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

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

关于java - 限制 PLAIN_MESSAGE JOptionPane 中输入文本的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50236799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com