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());
}
What's wrong with the code here?
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");
}