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/