package io.swtc; import com.github.sarxos.webcam.Webcam; import io.swtc.proccessing.WebcamCaptureLoop; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; @Deprecated public class SwingCameraWindow { private final JFrame frame; private final CameraPanel cameraPanel; private final WebcamCaptureLoop captureLoop; public SwingCameraWindow(Webcam webcam) { this.frame = new JFrame("scctv@" + webcam.getName()); this.frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // clean shit up frame.dispose(); captureLoop.stop(); // be sure to call this! otherwise the camera will stay open! } }); this.cameraPanel = new CameraPanel(); this.frame.add(cameraPanel); this.frame.pack(); this.frame.setSize(640, 480); this.captureLoop = new WebcamCaptureLoop(webcam, (BufferedImage img) -> SwingUtilities.invokeLater(() -> cameraPanel.setImage(img))); } public void open() { frame.setVisible(true); captureLoop.start(); } private static class CameraPanel extends JPanel { private BufferedImage currentImage; public void setImage(BufferedImage img) { this.currentImage = img; this.repaint(); // Triggers paintComponent } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (currentImage != null) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(currentImage, 0, 0, getWidth(), getHeight(), null); } } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { // init in edt Webcam webcam = Webcam.getDefault(); if (webcam != null) { SwingCameraWindow window = new SwingCameraWindow(webcam); window.open(); } else { JOptionPane.showMessageDialog( null, "No Webcam found!", "Error", JOptionPane.WARNING_MESSAGE ); } }); } }