Caprica Software

vlcj 4.x Tutorial

Mouse & Keyboard

This tutorial will show you how to build a media player application that can detect mouse and keyboard events on the video surface.


Let's Get Started

You should now already have a basic template for how to create a vlcj application, so this tutorial will no longer duplicate all of the code each time - instead we'll just show the new code fragments.


Template Methods

The EmbeddedMediaPlayerComponent provides template methods for all mouse events - you can override any of these methods to implement the behaviour you need. If you use these template methods everything should just work and you do not need to manage any listeners yourself.

Usage is pretty easy, you can either declare a separate sub-class of EmbeddedMediaPlayerComponent or you can just use an anonymous in-line class as we will do here:

mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
};

This example overrides a sub-set of the available template methods - a template method exists for each mouse event, mouse motion event, mouse wheel and key event.


Alternative to Template Methods

If you don't want to use template methods, you can always get the video surface from the media player component instance and add listeners yourself.

This fragment is equivalent to that demonstrated for the component above.

Component videoSurface = mediaPlayerComponent.videoSurfaceComponent();
videoSurface.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
}
});
videoSurface.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
}
});
videoSurface.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
}
});

Detecting mouse clicks should be straightforward, and if you target Linux then it is, but on Windows it requires some particular attention if you don't use the component template methods described above.

On Windows you must explicitly disable the native mouse and keyboard input handling.

mediaPlayer.inputApi().enableKeyInputHandling(false);
mediaPlayer.inputApi().enableMouseInputHandling(false);

This is not necessary on Linux.


Focus

Key events will only be delivered if your video surface has the input focus. This is usually achieved by a user clicking the video surface component, tabbing to it with the keyboard, or programmatically.

If is your responsibility to manage focus.

You can do this programmatically using:

mediaPlayerComponent.videoSurfaceComponent().requestFocus();

Alternatively, depending on your application this may work better:

mediaPlayerComponent.videoSurfaceComponent().requestFocusInWindow();