JOptionPane issue using internal dialog

2019-07-15 12:54发布

问题:

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

result value will be the inputted value.

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

result value will be null even you inputted a string.

temp is a panel that will contain in the JOptionPane. This JOptionPane will show on top of another customized JOptioPane.

回答1:

JOptionPane.showInternalInputDialog is to be used with JDesktopPane/JInternalFrames only, where this is the JDesktopPane/JInternalFrames instance.

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

If not used with either of the 2 above mentioned components it will not produce the correct output, in fact it will throw a Runtime Exception:

java.lang.RuntimeException: JOptionPane: parentComponent does not have a valid parent

UPDATE

As per your comments here is an example of how you would add JPanel to JDesktopPane and call JOptionPane#showInternalInputDialog. The important part is we need to call setBounds and setVisible on JPanel like we would as if it was JInternalFrame being added to the JDesktopPane, except of course we are adding a 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);