Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从actionPerformed和actionListener Java返回字符串_Java_Swing_Jframe_Actionlistener_Jfilechooser - Fatal编程技术网

从actionPerformed和actionListener Java返回字符串

从actionPerformed和actionListener Java返回字符串,java,swing,jframe,actionlistener,jfilechooser,Java,Swing,Jframe,Actionlistener,Jfilechooser,我已经创建了一个简单的程序,您可以在其中选择一个文件,并希望返回文件路径的字符串,我不太确定我在这里做错了什么 public static String createWindow() { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("JComboBox Test"); fra

我已经创建了一个简单的程序,您可以在其中选择一个文件,并希望返回文件路径的字符串,我不太确定我在这里做错了什么

public static String createWindow() {

    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JComboBox Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton inbutton = new JButton("Select Input File");

    inbutton.addActionListener(new ActionListener() {

       String imagePath;

       public void actionPerformed(ActionEvent ae) {
          JFileChooser fileChooser = new JFileChooser();
          int returnValue = fileChooser.showOpenDialog(null);
          if (returnValue == JFileChooser.APPROVE_OPTION) {
             File selectedFile = fileChooser.getSelectedFile();
             imagePath = selectedFile.getPath();
          }
       }
    });

    frame.add(inbutton);
    frame.pack();
    frame.setVisible(true);
    return imagePath;
}

您试图在调用该方法时立即返回一个值,但在发生某个事件之前,结果将不可用。你的逻辑错了。您应该做的是在模式对话框而不是JFrame中显示按钮。对话框的模式将有效地暂停从显示对话框的点开始的程序流,直到对话框不再可见。

错误是什么?请进一步解释,您期望的是什么,您实际得到的是什么?错误是imagePath无法解析为变量,我希望它包含文件路径。这应该是原始问题的一部分。返回语句在帧可见后立即执行。你没有机会点击按钮。在您有机会设置imagePath字段之后,您需要在ActivoperFormed模块中调用GUI模型类方法。阅读所有Oracle Java Swing教程。我该怎么做?我对java相当陌生,有没有建议的教程?@user1750156将其作为类中的一个字段。下次告诉我们你问题中的所有错误!查看Java Swing教程。@user1750156查看