动作侦听器仅在调试模式下工作

Action listener only working in debug mode

我在使用 vlcj 的媒体播放器上有一个动作侦听器。当我 运行 程序处于调试模式时,动作侦听器会在视频完成时触发,但是当我 运行 它通常在 eclipse 中它不会触发。

我的动作监听器

public static void youtubeGui(){

    Main.playing = true;
    final JFrame f = new JFrame();
    f.setLocation(100,100);
    f.setSize(1000,600);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.setVisible(true);

    Canvas c = new Canvas();
    c.setBackground(Color.black);
    JPanel p = new JPanel();
    p.setLayout(new BorderLayout());
    p.add(c);
    f.add(p);

    NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),"C:\Program Files\VideoLAN\VLC");
    Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);

    MediaPlayerFactory mpf = new MediaPlayerFactory();
    EmbeddedMediaPlayer emp = mpf.newEmbeddedMediaPlayer(new Win32FullScreenStrategy(f));
    emp.setVideoSurface(mpf.newVideoSurface(c));

    emp.setPlaySubItems(true);
    String str = Insert.videoQueue.peek();
    emp.prepareMedia(str);
    emp.play();
    Main.playing = true;
    try {
        TimeUnit.SECONDS.sleep(4);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    emp.addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
        @Override
        public void finished(MediaPlayer mediaPlayer) {
            Insert.videoQueue.remove();
            System.out.println("aaaaa");
            f.setVisible(false);
            f.dispose(); 
            Main.playing = false;
        }
    });

}

检查新插入方法

public static void addCheck(String locationIn) throws IOException {

    String fileLine = "";
    String a = "";

    while (true) {
        Scanner inFile = new Scanner(new FileReader(
        locationIn));
        while (inFile.hasNext()) {
            fileLine = inFile.nextLine();
        }

        if (fileLine.contains("watch?v=") && fileLine.contains("!add") && !fileLine.equals(a)) {
            a = fileLine;
            String result = fileLine.substring(fileLine.indexOf("[URL]") + 5, fileLine.indexOf("[/URL]"));
            videoQueue.add(result);
            result = "";
            if(Main.playing == false){
                Gui.youtubeGui();
            }
        }

        inFile.close();
    }
}

我猜是因为我怀疑您发布的代码没有说明全部情况。

我看到垃圾收集器在 Eclipse 中 运行 正常模式与调试模式下的行为不同。

如果您查看 youtubeGui 方法,您会将 mpfemp 声明为局部堆变量。当该方法退出时,似乎没有任何其他东西可以固定这两个变量,因此引用的对象有资格进行垃圾回收。

如果您的 emp 对象确实被垃圾回收了,这或许可以解释为什么您从未看到侦听器被激活。

在调试模式下,垃圾收集可能已被推迟,而在 non-debug 模式下它运行得更快。

你可能会想,媒体播放器怎么会因为视频还在播放就被垃圾回收了?好吧,媒体播放器已经在 J​​VM 的 外部 创建了一些 native 资源,并且仅仅因为 Java媒体播放器对象已被垃圾回收。通常会在某个不确定的时间之后发生的是本机崩溃。

所以我建议重新安排您的代码,以便您有一些东西可以硬引用您的媒体播放器(也许还有媒体播放器工厂)。