为什么JOptionPane.getValue()继续返回uninitializedValue

以下是我的代码

public static void main(String args[]){ JOptionPane pane = new JOptionPane(); pane.showInputDialog(null, "Question"); Object value = value.getValue(); System.out.println(value.toString()); --> this will print out uninitializedValue } 

我基本上想要检测用户何时单击JOptionPane中的取消以及用户何时关闭JOptionPane

你应该做这个:

  String s = JOptionPane.showInputDialog(null, "Question"); System.out.println(s); 

如果窗格关闭或按下取消,这将返回null字符串。

showInputDialog是一个静态方法,它不会修改JOptionPane 。 正如dogbane所指出的,你应该检查返回值showInputDialog

如果在实例上调用静态方法,某些编译器会生成警告,因此请始终检查编译器警告。 在你的情况下调用这样的方法:

 String result = JOptionPane.showInputDialog(null, "Question"); if(result == null){ //chancel pressed }else{ //normal code }