简体   繁体   English

从actionPerformed和actionListener Java返回String

[英]Returning String from actionPerformed and actionListener Java

I've created a simple program where you choose a file and, hopefully, have the string of the file path returned, I'm not quite sure what I'm doing wrong here. 我已经创建了一个简单的程序,你可以选择一个文件,希望返回文件路径的字符串,我不太清楚我在这里做错了什么。

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;
}

You're trying to return a value immediately when the method is called, but the result won't be available until some event occurs. 您正在尝试在调用方法时立即返回值,但在某些事件发生之前结果将不可用。 Your logic is off. 你的逻辑是关闭的。 What you should do is display the button in a modal dialog not a JFrame. 你应该做的是在模式对话框而不是JFrame中显示按钮。 The modality of the dialog will effectively pause program flow from the point where the dialog is displayed until the dialog is no longer visible. 对话框的模态将有效地暂停从显示对话框的点开始直到对话框不再可见的程序流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM