Karan Goel
Karan Goel

Reputation: 1117

Text Field shows twice in JOptionPane.showInputDialog. Why?

So, I'm creating a simple dialog to get user input, but the text field shows twice. Here's an SSCCE.

public static void main(String[] args) {
    JTextField fileName = new JTextField();
    Object[] message = {"File name", fileName};
    String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION);
    System.out.println(fileName.getText());
}

enter image description here

What's wrong with the code here?

Upvotes: 0

Views: 6081

Answers (2)

Vishal K
Vishal K

Reputation: 13066

It is doing so because you are adding JTextField object also in message[].

Object[] message = {"File name", fileName};//sending filename as message

So , the first JTextField shown is inherent one from inputDialog and other one is your own JTextField that you are sending as message .

What I guess is that you want to send the content of fileName to message. In that case your code should be like this:

public static void main(String[] args) {
    JTextField fileName = new JTextField();
    Object[] message = {"File name", fileName.getText()};//send text of filename
    String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION);
    System.out.println(fileName.getText());
}

UPDATE
If you want only to take input then there is no need to send object filename as message. You should simply proceed as follows:

public static void main(String[] args) {
        //JTextField fileName = new JTextField();
        Object[] message = {"File name"};
        String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION);
        if (option == null)
        System.out.println("Cancell is clicked..");
        else
        System.out.println(option+ " is entered by user");
    }

Upvotes: 4

Pshemo
Pshemo

Reputation: 124215

Input dialog by default contains text field so you don't need to add another one. Try maybe this way

String name = JOptionPane.showInputDialog(null, "File name",
        "Add New", JOptionPane.OK_CANCEL_OPTION);
System.out.println(name);

Upvotes: 2

Related Questions