JFrame 没有完全关闭

JFrame doesn't get closed completely

我正在使用 VLCJ 绑定来创建视频播放器。

我的代码:

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

我通过 new VideoPlayer(source) 从另一帧调用此视频播放器。 当我使用JFrame.DISPOSE_ON_CLOSE时,框架关闭但声音仍然不响..

如何完全关闭视频播放器框架?

使用JFrame.EXIT_ON_CLOSE

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The exit application default window close operation. If a window has this set as the close operation and is closed in an applet, a SecurityException may be thrown. It is recommended you only use this in an application.

https://docs.oracle.com/javase/8/docs/api/javax/swing/JFrame.html#EXIT_ON_CLOSE

如果您不想使用 Exit on close 这将关闭您的应用程序,那么

在windowClosing上添加一个监听器,当监听器调用该方法时停止音频

frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        System.out.println("Closed");
        //Here stop the audio
        e.getWindow().dispose();
    }
});
  1. 将关闭操作声明为JFrame.DO_NOTHING_ON_CLOSE
  2. 添加一个WindowListener如下(根据需要适应你的代码):

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

可能需要将 framemediaPlayerComponent 声明为 final 以便从内部 class.

访问它们