【问题标题】:JOptionPane issue using internal dialog使用内部对话框的 JOptionPane 问题
【发布时间】:2012-12-14 13:05:45
【问题描述】:
String result = JOptionPane.showInputDialog(this, temp);

result 值将是输入的值。

String result = JOptionPane.showInternalInputDialog(this, temp);

result 即使你输入了一个字符串,值也会为空。

temp 是一个将包含在 JOptionPane 中的面板。此 JOptionPane 将显示在另一个自定义 JOptionPane 之上。

【问题讨论】:

  • 我的意思是输出。为什么不一样?
  • 如果您没有很快得到合适的答案,请考虑创建并发布sscce

标签: java swing joptionpane


【解决方案1】:

JOptionPane.showInternalInputDialog 只能与JDesktopPane/JInternalFrames 一起使用,其中thisJDesktopPane/JInternalFrames 实例。

final JDesktopPane desk = new JDesktopPane();
...
String s=JOptionPane.showInternalInputDialog(desk, "Enter Name");

如果不与上述两个组件中的任何一个一起使用,它将不会产生正确的输出,实际上它会抛出一个运行时异常:

java.lang.RuntimeException: JOptionPane: parentComponent 没有 有效的父母

更新

根据您的 cmets,这里有一个示例,说明如何将 JPanel 添加到 JDesktopPane 并调用 JOptionPane#showInternalInputDialog。重要的部分是我们需要在JPanel 上调用setBoundssetVisible,就像我们将JInternalFrame 添加到JDesktopPane 一样,当然我们要添加JPanel

JFrame frame = new JFrame("JInternalFrame Usage Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// A specialized layered pane to be used with JInternalFrames
jdpDesktop = new JDesktopPane() {
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(600, 600);
    }
};

frame.setContentPane(jdpDesktop);

JPanel panel = new JPanel();
panel.setBounds(0, 0, 600, 600);

jdpDesktop.add(panel);

frame.pack();
frame.setVisible(true);

panel.setVisible(true);

String result = JOptionPane.showInternalInputDialog(jdpDesktop, "h");

System.out.println(result);

【讨论】:

  • 1+。你可能是对的,每次我看到this 作为这些方法之一的参数时我都会不寒而栗,因为这表明@Juan 犯了一个错误,即不必要地让他的类扩展 JFrame 或其他一些顶级 GUI 窗口。
  • @HovercraftFullOfEels 很好的调查技巧,很可能是正确的。
  • @JuanMatanong 请查看我的编辑。 showInternalInputDialog 只能与 JDesktopPanes/JInternalFrames 一起使用,否则将不起作用(即不会显示选项窗格并引发异常)
  • @DavidKroukamp,我只是在学习JPanel 课程。我怎样才能把它放到JDesktopPane/JInternalFrame
  • 您确定需要这个吗?因为我不明白你为什么要在你可以使用showInputDialog 时做所有这些,这意味着JFrames、JPanels 等
猜你喜欢
  • 1970-01-01
  • 2013-12-05
  • 2012-01-31
  • 2011-12-09
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 2012-08-27
相关资源
最近更新 更多