4

我正在尝试在 JPanel 中使用 vlcj 播放视频,但它对我不起作用。我收到的消息异常是 "java.lang.IllegalStateException: The video surface component must be displayable" ,这与Keep getting an Error "Component must be displayable"中的问题相同。

包含画布和 vlcj 播放器的 JPanel 的代码是这样的:

import javax.swing.JPanel;

import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;

import java.awt.Canvas;
import java.awt.Color;

import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.player.embedded.videosurface.CanvasVideoSurface;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import uk.co.caprica.vlcj.runtime.windows.WindowsCanvas;

public class MyJPanel extends JPanel {
private EmbeddedMediaPlayer player;
private WindowsCanvas canvas;

public MyJPanel() {
    canvas = new WindowsCanvas();
    add(canvas);
    revalidate();
    repaint();

    canvas.setVisible(true);

    MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
    player = mediaPlayerFactory.newEmbeddedMediaPlayer();

    CanvasVideoSurface videoSurface = mediaPlayerFactory.newVideoSurface(canvas);

    player.setVideoSurface(videoSurface);
    player.playMedia("v.avi");   // This sentence throws the exception.
}
}

MyJFrame 扩展了 JFrame 并且仅包含 MyJPanel JPanel。我认为这根本不重要。

import javax.swing.JFrame;

public class MyJFrame extends JFrame {
protected MyJPanel myJPanel;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MyJFrame frame = new MyJFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public MyJFrame() {
    myJPanel = new myJPanel();
    add(myJPanel);
}   
}

提前致谢。

4

1 回答 1

8

您正在尝试在包含画布的框架设置为可见之前播放媒体。您需要将playMedia()调用放在一个单独的方法中,并在创建整个框架并将其设置为可见后调用它。

编辑:

如果您仍然希望它直接播放,只需在创建框架并使其可见后调用相关方法:

MyJFrame frame = new MyJFrame();
frame.setVisible(true);
frame.startPlaying();

...显然,您需要startPlaying()在 MyJFrame 上进行定义,但它应该立即开始播放。你只需要先设置可见的框架。

于 2012-05-16T15:52:28.697 回答