Search code examples
javaswinguser-interfacejtextareajoptionpane

JOptionPane with a JTextArea instead of a text field?


I need to grab multiple lines of input from a popup JOptionPane (or some other popup, but most of my searches direct me there, which is where I get stuck..). I am stuck at using

JOptionPane.showInputDialog(null, new JTextArea(20,20));

but I want just the 20x20 area to be read to a String and no text field shown. I figure there must be some way to do this, but the other types of dialog only seem to return an int... It doesn't have to be a JOptionPane, as long as it is a separate popup from my main GUI that can read a string back in to be read.


Solution

  • Keep a reference to the JTextArea before passing to the JOptionPane, the JOptionPane will tell you what the user did (how they closed the dialog) and depending on the result, you might want to do different things

    JTextArea ta = new JTextArea(20, 20);
    switch (JOptionPane.showConfirmDialog(null, new JScrollPane(ta))) {
        case JOptionPane.OK_OPTION:
            System.out.println(ta.getText());
            break;
    }
    

    See How to Make Dialogs for more details