Search code examples
javaswingvlclibvlcvlcj

JFrame doesn't get closed completely


I am using VLCJ binding to create a video player.

My code:

public class MyVideoPlayer {

    private EmbeddedMediaPlayerComponent mediaPlayerComponent;
    static String VLCLIBPATH = "C:\\Program Files\\VideoLAN\\VLC";

    public MyVideoPlayer(String source) {
        NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), VLCLIBPATH);
        Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
        JFrame frame = new JFrame("VLC Player");
        mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        frame.setContentPane(mediaPlayerComponent);
        frame.setSize(1366, 768);
        frame.setVisible(true);
        mediaPlayerComponent.getMediaPlayer().playMedia(source);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    } 
}

I call this video player from another frame by new VideoPlayer(source). When I use JFrame.DISPOSE_ON_CLOSE, the frame gets closed but the sound still won't go..

How can I close the video player frame completely?


Solution

    1. Declare the close operation as JFrame.DO_NOTHING_ON_CLOSE.
    2. Add a WindowListener as follows (adapt to your code as needed):

      frame.addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              mediaPlayerComponent.getMediaPlayer().stop(); // Very important!
              frame.dispose();
          }
      });
      

    It will likely be necessary to declare frame & mediaPlayerComponent as final in order to access them from within an inner class.