Skip to content

Instantly share code, notes, and snippets.

@lppedd
Last active February 5, 2021 13:56
Show Gist options
  • Select an option

  • Save lppedd/8b834e08573fbf25ce564c97296e4d1e to your computer and use it in GitHub Desktop.

Select an option

Save lppedd/8b834e08573fbf25ce564c97296e4d1e to your computer and use it in GitHub Desktop.
JPanel frames
package example;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
public class HelloApp {
private final JLabel videoLabel;
public static void main(final String[] args) {
EventQueue.invokeLater(() -> {
final HelloApp window = new HelloApp();
});
}
public HelloApp() {
final JFrame frame = new JFrame("MULTIPLE-TARGET TRACKING");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
final int width = 800;
final int height = 500;
frame.setBounds(0, 0, width, height);
frame.setLayout(new BorderLayout());
// Show the frame at the center of the screen
frame.setLocation(
(int) (0.5 * Toolkit.getDefaultToolkit().getScreenSize().width - width / 2),
(int) (0.5 * Toolkit.getDefaultToolkit().getScreenSize().height - height / 2)
);
frame.setVisible(true);
final JPanel panel = new JPanel(new BorderLayout());
frame.getContentPane().add(panel, BorderLayout.CENTER);
videoLabel = new JLabel();
panel.add(videoLabel, BorderLayout.CENTER);
final JButton startButton = new JButton("START / REPLAY");
startButton.addActionListener(event -> {
// Frame processing should run in a separate (non-EDT) thread to avoid freezing the UI.
// To spawn a thread you can use a bare Thread, or look at ExecutorService.
//
// Also remember not to press the button more than once, or multiple threads
// will be updating the shown image
final Thread thread = new Thread(() -> {
try {
playVideo();
} catch (final InterruptedException | InvocationTargetException ex) {
ex.printStackTrace();
}
});
thread.start();
}
);
panel.add(startButton, BorderLayout.PAGE_START);
}
private void playVideo() throws InterruptedException, InvocationTargetException {
// Loop to showcase how the images change inside the JLabel
while (true) {
for (int i = 1; i < 6; i++) {
// Here we process the frame.
// Replace this with whatever you need to do
final URL resource = getClass().getResource("/img" + i + ".jpg");
// Update the shown image using the EDT thread, otherwise an exception will be thrown
EventQueue.invokeAndWait(() -> {
final Icon image = new ImageIcon(resource);
videoLabel.setIcon(image);
});
// Simulate 20 FPS, to be removed
Thread.sleep(50);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment