Search code examples
javadisposeactionlistener

how to add actionlisten upon dispose


i want to stop the Sound when the windows gets closed, how can i add an actionlistner upon dispose?

 public Tetris(boolean sound) {

    statusbarLabel = new JLabel(" 0");
    add(statusbarLabel, BorderLayout.SOUTH);
    Board board = new Board(this);
    if(sound){
        Sound.gameSound.play();
    }

    add(board);
    board.start();


    setSize(200, 400);
    setTitle("Tetris");
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);

}


Solution

  • The easiest way would be to add a WindowListener:

    addWindowListener(new WindowAdapter() {
    
       @Override
       public void windowClosing(WindowEvent e) {
         Sound.gameSound.stop();
       }
    });