如何更改JOptionPane.showInputDialog中按钮的默认文本

14

我想将 JOptionPane.showInputDialog 中“确认”和“取消”按钮的文本设置为自定义字符串。

JOptionPane.showOptionDialog 中有一种方法可以更改按钮的文本,但我找不到在 showInputDialog 中更改文本的方法。

4个回答

20

如果你不想仅仅针对一个输入对话框进行设置,那么在创建对话框之前添加以下这些行。

UIManager.put("OptionPane.cancelButtonText", "nope");
UIManager.put("OptionPane.okButtonText", "yup");

其中 'yup' 和 'nope' 是您想要显示的文本


如果你只想在一个对话框中使用它,之后可以立即更改回去。 - hjk321

14

下面的代码应该会弹出一个对话框,你可以在Object[]中指定按钮文本。

Object[] choices = {"One", "Two"};
Object defaultChoice = choices[0];
JOptionPane.showOptionDialog(this,
             "Select one of the values",
             "Title message",
             JOptionPane.YES_NO_OPTION,
             JOptionPane.QUESTION_MESSAGE,
             null,
             choices,
             defaultChoice);

另外,请务必查看Oracle网站上的Java教程。我在这个链接的教程中找到了解决方案:http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#create


9
如果您想使用自定义按钮文本的JOptionPane.showInputDialog,您可以扩展JOptionPane:
public class JEnhancedOptionPane extends JOptionPane {
    public static String showInputDialog(final Object message, final Object[] options)
            throws HeadlessException {
        final JOptionPane pane = new JOptionPane(message, QUESTION_MESSAGE,
                                                 OK_CANCEL_OPTION, null,
                                                 options, null);
        pane.setWantsInput(true);
        pane.setComponentOrientation((getRootFrame()).getComponentOrientation());
        pane.setMessageType(QUESTION_MESSAGE);
        pane.selectInitialValue();
        final String title = UIManager.getString("OptionPane.inputDialogTitle", null);
        final JDialog dialog = pane.createDialog(null, title);
        dialog.setVisible(true);
        dialog.dispose();
        final Object value = pane.getInputValue();
        return (value == UNINITIALIZED_VALUE) ? null : (String) value;
    }
}

您可以这样调用:
JEnhancedOptionPane.showInputDialog("Number:", new Object[]{"Yes", "No"});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接