我尝试将 VLCJ 播放器放在 Canvas 内。
我已经阅读了很多关于它的主题,但我仍然无法实现我想做的事情。
这是我使用的代码:
public class RaspberryControler extends JFrame
{
/*Have to declare it in order to use vlcj*/
private EmbeddedMediaPlayerComponent mediaPlayerComponent;
private EmbeddedMediaPlayer mediaPlayer;
public RaspberryControler(String host){
this.host = host;
controler = new Controler(this);
initComponents();
}
private void initComponents(){
setBasicParameters();
createMainPanel();
createControlPanel();
createWebcamPanel();
mainPanel.add(webcamPanel);
mainPanel.add(controlPanel);
setListeners();
/*Set the last parameters of the frame*/
this.revalidate();
this.repaint();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
}
private void createMainPanel(){
mainPanel = new JPanel();
/*Set the Layout*/
mainPanel.setLayout(new FlowLayout());
mainPanel.setVisible(true);
/*Set the parameters*/
this.getContentPane().add(mainPanel);
}
private void createWebcamPanel(){
/*Get the VLC Libraries*/
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:/VLC/VideoLAN/VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
/*Create components*/
liveStream = new JLabel("Live Stream");
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
/*Set parameters of the components*/
liveStream.setPreferredSize(new Dimension(200, 30));
liveStream.setHorizontalAlignment(SwingConstants.CENTER);
/*Set the layout*/
webcamPanel = new JPanel();
webcamPanel.setLayout(new BorderLayout());
webcamPanel.setPreferredSize(new Dimension(550, 480));
webcamPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
/*Place the components*/
webcamPanel.setVisible(true);
webcamPanel.add(liveStream, BorderLayout.NORTH);
webcamPanel.add(mediaPlayerComponent, BorderLayout.CENTER);
this.setVisible(true);
try{
mediaPlayerComponent.getMediaPlayer().playMedia("http://127.0.0.1:8989/movie");
}catch(IllegalStateException e){
System.out.println(e.toString());
}
}
然后,当然,WebcamPanel 被添加到当前的 JFrame 中。
我做错了什么 ?
这是输出:
The video surface component must be displayable
感谢那些会回应的人!Ps:这是我检查的主题:
- https://github.com/caprica/vlcj/issues/29
- Failed to play video by vlcj in java
最佳答案
您实际上并没有准确地说出什么不起作用。
从表面上看,您似乎缺少布局约束。
大概是这样的:
webcamPanel.add(canvas);
应该是这样的:
webcamPanel.add(canvas, BorderLayout.CENTER);
否则,您将使用
null
添加您的 Canvas 布局约束。“视频组件必须是可显示的”错误是因为在用户界面可显示之前您无法播放视频 - VLC 没有有效的 Canvas 窗口句柄,直到您
pack()
框架,或使其可见。简而言之,在播放视频之前,您应该执行 frame.setVisible(true)
.关于线程,应用通常的 Swing 线程规则 - 即您必须确保在事件调度线程 (EDT) 上调用对 UI 组件的更改。通常你不需要担心这个,比如当你响应一个 Swing 事件监听器时。如果您有一个启动 Swing 组件的创建或操作的后台线程(不是 Swing EDT),您只需要担心这一点。如果您需要这样做,请使用
invokeLater
在 SwingUtilities
类(class)。我认为您的情况不需要这样做,但是如果没有更多代码,就很难说。稍微偏离主题但相关的评论:使用现代版本的 vlcj,有更简单的方法可以做到这一点,例如通过使用
EmbeddedMediaPlayerComponent
它负责媒体播放器、视频表面和相关的 Canvas
为你。您只需将组件添加到布局中即可。
关于java - 在 Canvas 中显示 VLCJ 播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26606404/