如何将变量从try传递到动作事件?

时间:2018-11-25 22:50:52

标签: 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();
    });
  • 感觉这应该很简单,但是我什么都找不到

1 个答案:

答案 0 :(得分:1)

将代码移动到访问try块内的变量,或者在try块外声明变量,并确保在注册事件处理程序时将其初始化。

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