将 JTextField 添加到 JOptionPane 中:ShowOptionDialog

Adding a JTextField into a JOptionPane: ShowOptionDialog

我想知道是否可以将 JTextField 添加到 ShowOptionDialog 框。

     int optionChosen = JOptionPane.showOptionDialog(finishPayInput,     
     dialogPanel, "The Title", JOptionPane.NO_OPTION,      
     JOptionPane.QUESTION_MESSAGE, null, options , options[0]); 

当我运行程序时,对话框显示,但JTextField不显示。

您不能将文本字段添加到 JOptionPane.showOptionDialog 第一个参数是父组件而不是子组件。

查看 documentation:

public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException

Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter. If optionType is YES_NO_OPTION, or YES_NO_CANCEL_OPTION and the options parameter is null, then the options are supplied by the look and feel.

The messageType parameter is primarily used to supply a default icon from the look and feel. Parameters:parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is usedmessage - the Object to displaytitle - the title string for the dialogoptionType - an integer designating the options available on the dialog: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, or OK_CANCEL_OPTIONmessageType - an integer designating the kind of message this is, primarily used to determine the icon from the pluggable Look and Feel: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGEicon - the icon to display in the dialogoptions - an array of objects indicating the possible choices the user can make; if the objects are components, they are rendered properly; non-String objects are rendered using their toString methods; if this parameter is null, the options are determined by the Look and FeelinitialValue - the object that represents the default selection for the dialog; only meaningful if options is used; can be nullReturns:an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialogThrows:HeadlessException - if GraphicsEnvironment.isHeadless returns trueSee Also:GraphicsEnvironment.isHeadless()

当然可以。 最简单的解决方案:

JTextField txt = new JTextField();
JOptionPane.showOptionDialog(null, finishPayInput, "The Title", JOptionPane.NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, null, null);

但是,如果您只想显示 JTextField(以获取用户输入),最好的办法是使用 JOptionPane.showInputDialog:

JOptionPane.showInputDialog(null, "Insert value: ", "The title", JOptionPane.QUESTION_MESSAGE);