You have to check the return value for null and then invoke the method trim
String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");
if(response!=null)
response = response.trim()+".xml";
Вопрос
String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");
This throws a null pointer error if the user x's out of the optionpane
Firstly, why can't response hold a null value?
secondly, how do i handle this?
full code:
String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:").trim() + ".xml";
if(response != null){
File newData = new File("src\\golfdatabase\\Databases\\" + response);
try {
newData.createNewFile();
databaseComboBox.addItem(response);
} catch (IOException ex) {
Logger.getLogger(GolfDriver.class.getName()).log(Level.SEVERE, null, ex);
}
databaseComboBox.setSelectedItem(response);
disableButtonsNullList(false);
}
Решение
You have to check the return value for null and then invoke the method trim
String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");
if(response!=null)
response = response.trim()+".xml";
Другие советы
It gives null back when you click on "Cancel" try something like that:
String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");
if(response != null){
response = response.trim() + ".xml";
}
Take note that: String response = JOptionPane.showInputDialog(....);
Would have been enough to create the JOptionPane.
Firstly: Yes responses CAN hold a null value, but your code snippet does not show how you handle the responses so there is no way for me to tell why it is throwing them.
Secondly: That again depends on how you are handling the responses, please elaborate more on your code.
EDIT: try adding a String cast as the java tutorial suggests you do: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
EDIT2: While Octopus found the problem in a piece of code (that I shamefully overlooked) please keep in mind the above points because they still hold true.