java - 如何将变量从 try 传递到 action 事件?

标签 java javafx

try(FileInputStream fis = (new FileInputStream("*FILE*"))){
            Player player = new Player(fis);
            Button btn = new Button();
            btn.setText("Start");
            Button btn2 = new Button();
            btn2.setText("Stop");
        }catch(JavaLayerException | IOException e ){
            e.printStackTrace();
        }

    btn.setOnAction((ActionEvent event) -> {
        this.player = player;
        try{
            new playMusic(player).start();
        }catch(Exception e){
            e.printStackTrace();
        }
    });

    btn2.setOnAction((ActionEvent event)->{
        player.close();
    });
  • 感觉这应该是非常简单的东西,但我到处都找不到

最佳答案

要么将访问变量的代码移到 try block 内,要么在 try block 外声明变量,并确保在注册事件处理程序时初始化它.

final Player player;
try(FileInputStream fis = new FileInputStream("*FILE*")){
    player = new Player(fis);
} catch(JavaLayerException | IOException e){
    e.printStackTrace();

    // prevent access to uninitialized player variable by exiting the method
    throw new RuntimeException(e);
}

Button btn = new Button();
btn.setText("Start");
Button btn2 = new Button();
btn2.setText("Stop");

btn.setOnAction((ActionEvent event) -> {
    this.player = player;
    try{
        new playMusic(player).start();
    } catch(Exception e){
        e.printStackTrace();
    }
});

btn2.setOnAction((ActionEvent event)->{
    player.close();
});

代替

throw new RuntimeException(e);

您也可以优雅地退出该方法,使用

return;

相反。


编辑

如果 Player 没有读取构造函数中的所有代码,您一定不要关闭它。不过,try-with-resources 可以做到这一点。更改为 try catch

try {
    FileInputStream fis = new FileInputStream("*FILE*");
    try {
        player = new Player(fis);
    } catch(JavaLayerException | IOException e) {
        e.printStackTrace();
        fis.close(); // close stream on player creation failure

        // prevent access to uninitialized player variable by exiting the method
        throw new RuntimeException(e);
    }
} catch(IOException e){
    e.printStackTrace();

    // prevent access to uninitialized player variable by exiting the method
    throw new RuntimeException(e);
}

关于java - 如何将变量从 try 传递到 action 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472792/

相关文章:

全屏 Java Fx 整个应用程序

java - 无法连接 mkdir() JavaFX 的日期和文件名

java - 使用 Spring 批处理处理大文件的最佳方法

java - 如何从 for 循环关系中创建循环关系

java - 运行JavaFx媒体应用程序时出现模块错误

java - 带有自定义对象的 FIlteredList

css - 使用像 FireBug 这样的工具调试 JavaFx

java - 在 DAO 层的 JUnit 中找不到当前线程的 session

java - Servlet 的 ProxyPass?

java - Jackson objectMapping 没有获取 JSON 数据