package ui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
import webcam.ImageDownloadFailedException;
import webcam.WCVCam;
@SuppressWarnings("serial")
public class WCVCamPanel extends JPanel implements Runnable {
private boolean lineBorder, refreshFailed;
private WCVCam cam;
private String camLabel;
private Thread refreshThread;
public WCVCamPanel(WCVCam cam) {
this.cam = cam;
this.refreshThread = null;
this.refreshFailed = true;
this.lineBorder = false;
this.camLabel = cam.getCamName();
}
public WCVCamPanel() {
this.lineBorder = false;
this.refreshThread = null;
this.refreshFailed = true;
this.cam = new WCVCam("Webcam Viewer", "", "-----");
this.camLabel = "Webcam Viewer";
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(!refreshFailed) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(cam.getImage(false), (int) cam.getViewOffsets().getWidth(),
(int) cam.getViewOffsets().getHeight(), this);
g.setColor(Color.ORANGE);
g.setFont(new Font("Serif", Font.BOLD, 12));
g.drawString(camLabel, 4, 14);
g.setColor(Color.BLACK);
if(lineBorder) g.drawRect(0, 0, getWidth()-1, getHeight()-1);
}
else paintLoadingScreen();
}
public void paintLoadingScreen() {
Graphics g = getGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.ORANGE);
g.setFont(new Font("Serif", Font.BOLD, 12));
g.drawString("Loading " + camLabel + " Webcam...", 4, 14);
}
public void refreshDisplay() {
paintLoadingScreen();
System.out.println("Loading " + camLabel);
if(refreshThread != null && refreshThread.isAlive()) {
refreshThread.interrupt();
System.out.println("Interupted Download");
}
refreshThread = new Thread(this, "Refresh Webcam Thread");
refreshThread.start();
}
public void run() {
cam.setScaleDimension(this.getSize());
new Thread(cam).start();
try{
if(cam.isReady()) {
camLabel = cam.getCamName();
refreshFailed = false;
repaint();
}
}
catch(ImageDownloadFailedException e) {
camLabel = e.getMessage();
refreshFailed = true;
repaint();
}
catch(InterruptedException e) {
}
}
//Setters
public void setBorder(boolean border) {
this.lineBorder = border;
}
public void setCam(WCVCam cam) {
this.cam.clearCamMemory();
this.cam = cam;
this.camLabel = cam.getCamName();
}
//Getters
public WCVCam getCam() {
return cam;
}
}