有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将变量从尝试传递到操作事件?

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) 个答案

  1. # 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{}

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