Compiling Java Applets - java

I recently started making a Java applet game for the java4k game contest but I'm new with applets and I have some questions about them.
I have an applet written in eclipse and I can run it in eclipse using applet viewer but how do I compile it? There doesn't seem a option for compiling applets..
..and what is a jar archive?
Thanks.
Also here's my source in case you need it:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;
public class game extends Applet implements KeyListener{
private static final long serialVersionUID = 1L;
public int x = 50,y = 50;
public boolean right, left, down, up, lt = false, rt = true;
public Image buffer;
BufferedImage img = null;
BufferedImage imgl = null;
Graphics bg;
public void init(){
try {
img = ImageIO.read(new File("C:/player.png"));
} catch (IOException e){}
try {
imgl = ImageIO.read(new File("C:/playerl.png"));
} catch (IOException e){}
addKeyListener(this);
setSize(400,200);
setBackground(Color.cyan);
Timer t = new Timer();
t.schedule(new TimerTask(){public void run(){
if (right == true){x++;}
if (left == true){x--;}
if (up == true){y--;}
if (down == true){y++;}
repaint();
}},10,10);
buffer = createImage(400,200);
bg = buffer.getGraphics();
}
public void paint(Graphics g){
bg.setColor(Color.WHITE);
//bg.clearRect(0, 0, 400, 200);
if (rt == true){
bg.drawImage(img,x,y, this);
}
if (lt == true){
bg.drawImage(imgl,x,y, this);
}
g.drawImage(buffer,0,0,this);
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == 37){
left = true;
lt = true;
rt = false;
}
if (e.getKeyCode() == 39){
right = true;
rt = true;
lt = false;
}
if (e.getKeyCode() == 38){
up = true;
}
if (e.getKeyCode() == 40){
down = true;
}
}
public void keyReleased(KeyEvent e){
if (e.getKeyCode() == 37){
left = false;
}
if (e.getKeyCode() == 39){
right = false;
}
if (e.getKeyCode() == 38){
up = false;
}
if (e.getKeyCode() == 40){
down = false;
}
}
public void update(Graphics g){
paint(g);
}
}

You will need to export as a JAR file. To do this you will need to right-click the project > export.
Select Java > JAR file
In the JAR Export Dialog, select what parts you want to export (Export generated class files and resources) for your project. Probably want to specify the output folder as well. The rest of the options can be left as default and go to Finish.
You can run the JAR in a applet viewer or from a webpage in an APPLET tag, make sure to set the archive="jar file name".

In Eclipse, right click the project, click export, and export as a jar.
Then you can embed this jar in your webpage to be run as an applet, or externally with appletviewer.
There's no difference between a JAR and an Archive Jar. JAR stands for "Java ARchive".

You cant create self executive jar without main method.
Fortunately it's quite simple to do it.
You can create method called public static void main(String[] args) within your main class.
and then do something like this:
yourmainclassname yourname = new yourmainclassname(); //create new object
yourname.init(); //invoke the applet's init() method
yourname.start(); //starts the applet
// Create a window (JFrame) and make applet the content pane.
JFrame window = new JFrame("Put something here");
window.setSize(640, 480); //size in pixels
window.setContentPane(theApplet); //
window.setVisible(true);
window.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
That's all. Next you can just export project to self executive JAR.

Related

Illegal Argument Exception- name

I have searched for the past few days for a solution to this problem and I am beating my head against the wall. I'm knew to programming in java so bear with me.
I am currently trying to implement a Java Applet into an HTML page of mine for a school project. The Applet runs fine in Eclipse using AppletViewer, as well as in the web browser in a program called Blue Jay. I have exported the program into a jar file in the same directory as my HTML page, and added the necessary code to my HTML file, but whenever I actually run the HTML file the Applet gives me an "Illegal Argument Exception: name" error. The details of the error include the phrase "java.net.MalformedURLException:unknown protocol:e."
This is the relevant code for my HTML file:
<applet code="MovingBoxes.class" archive="E:\WebSystems\WebPages\Animations.jar"
width="350" height="350" >Animation of moving boxes</applet>
When the error occurs the phrase inside of the applet tags is not displayed either if that is significant. I have tried exporting other applets to see if they work and have received the same error every time. I'm also fairly certain that the destination for the file is correct, because when I change the destination name to something incorrect a "Class Not Found" error occurs instead.
And in the off chance that the error is in my applet, here is my applet code.
package theBig;
import java.awt.*;
public class MovingBoxes extends java.applet.Applet implements Runnable
{
Thread runner;
int size = 15;
int x_value = 200;
int y_value = 175;
int rndm_x;
int rndm_y;
int move = 1;
int cntr = 0;
Image dbImage;
Graphics dbg;
int x_value2 = 240;
int y_value2 = 250;
int rndm_x2;
int rndm_y2;
public void start()
{
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
if (runner != null) {
runner.stop();
runner = null;
}
}
public void run()
{
setBackground(Color.white);
while (true) {
rndm_x = (int)(Math.random()*10+1);
rndm_y = (int)(Math.random()*10+1);
if (rndm_x > 5)
x_value += move;
else
x_value -= move;
if (rndm_y > 5)
y_value = 50;
else
y_value = 50;
rndm_x2 = (int)(Math.random()*10+1);
rndm_y2 = (int)(Math.random()*10+1);
if (rndm_x2 > 5)
x_value2 += move;
else
x_value2 -= move;
if (rndm_y2 > 5)
y_value2 = 50;
else
y_value2 = 50;
if (x_value + size > x_value2)
{
cntr = 50;
}
while(cntr > 0)
{
cntr --;
x_value --;
x_value2 ++;
repaint();
try { Thread.sleep(25); }
catch (InterruptedException e) { }
}
repaint();
try { Thread.sleep(25); }
catch (InterruptedException e) { }
}
}
public void update(Graphics g) {
dbImage = createImage(getWidth(),getHeight());
dbg = dbImage.getGraphics();
paint(dbg);
g.drawImage(dbImage,0,0,this);
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect(x_value, y_value, size, size);
g.fillRect(x_value, y_value, size, size);
g.setColor(Color.blue);
g.drawRect(x_value2, y_value2, size, size);
g.fillRect(x_value2, y_value2, size, size);
}
} `
Like I said, I have searched everywhere for an answer and come up empty handed. Any help you can offer me is greatly appreciated.
Maybe its a typo but you are missing a " after .jar in your HTML code.
If that doesn't help, maybe your archive should be a URL, not just a file path. Can you try this:
<applet code="MovingBoxes.class" archive="file:/E:/WebSystems/WebPages/Animations.jar"
width="350" height="350" >Animation of moving boxes</applet>

Using image in place of Rectangle in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
It's my first time trying to create a 2d game in java and I made a little 8-bit like character that I want to put in place of the rectangle that appears on screen. I can't quite understand how to get the .png image into the rectangle's place, or how I would go about making the character, in this case, the image saved to my hard drive. Thanks!
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Keying extends JPanel {
public Rectangle character;
public int charW = 24;
public int charH = 36;
public boolean right = false;
public boolean left = false;
public boolean up = false;
public boolean down = false;
public Keying(Display f, Images i)
{
character = new Rectangle(180, 180, charW, charH);
f.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_D)
{
right = true;
}
if (e.getKeyCode() == KeyEvent.VK_A)
{
left = true;
}
if (e.getKeyCode() == KeyEvent.VK_S)
{
down = true;
}
if (e.getKeyCode() == KeyEvent.VK_W)
{
up = true;
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_D)
{
right = false;
}
if (e.getKeyCode() == KeyEvent.VK_A)
{
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_S)
{
down = false;
}
if (e.getKeyCode() == KeyEvent.VK_W)
{
up = false;
}
}
});
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.white);
g.setColor(Color.black);
g.fillRect(character.x, character.y, character.width, character.height);
if (right)
{
character.x += 1;
}
if (left)
{
character.x -= 1;
}
if (down)
{
character.y += 1;
}
if (up)
{
character.y -= 1;
}
repaint();
}
}
The process is relatively simple...
Start by loading the character image...
public class Keying extends JPanel {
//public Rectangle character;
private java.awt.BufferedImage character;
private java.awt.Point characterLocation;
//...
public Keying(Display f, Images i) throws IOException
{
character = javax.ImageIO.read(...);
characterLocation = new Point(0, 0);
//...
See Reading/Loading an Image for more details...
Then, you simply want to paint the character image...
#Override
protected void paintComponent(Graphics g)
{
g.drawImage(character, characterLocaiton.x, characterLocation.y, this);
Advice
Avoid KeyListener, it's prone to focus issues you really don't want to deal with. Instead use key bindings, see How to Use Key Bindings for more details
Avoid putting any logic within any of the paint routines, painting can occur at any time, many of which you don't control, this could have your character moving in directions you don't expect or faster than they should. Instead, this belongs within the main game loop which is responsible for updating the state and scheduling paint requests.
NEVER change the state of the component from within any paint method, this could cause an infinite loop of paint requests, which will consume your systems resources. Within your context, don't call setBackground (by the time you call this, the background has already been painted anyway) or repaint

java.lang.NullPointerException Issue When Attempting to Run Program [duplicate]

This question already has answers here:
Class.getResource() returns null
(2 answers)
Closed 8 years ago.
This is my first question, I hope it's not too poorly made.
I'm definitely beginner level at java, probably lower. I'm taking most of my code from a tutorial in fact, hoping I'll learn what all the things do soon enough.
Anyway, so far, I have 3 .java files in my program, and it shows the exception to be at all 3 of them, plus one I never made.
Here's the full error:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at Emilia.<init>(Emilia.java:17)
at Board.<init>(Board.java:26)
at TestGame.<init>(TestGame.java:7)
at TestGame.main(TestGame.java:18)
Here's all the code:
TestGame.java
import javax.swing.JFrame;
public class TestGame extends JFrame {
public TestGame() {
add(new Board());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setTitle("Project Obcasus");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new TestGame();
}
}
Board.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener {
private Timer timer;
private Emilia emilia;
public Board() {
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
emilia = new Emilia();
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(emilia.getImage(), emilia.getX(), emilia.getY(), this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
emilia.move();
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
emilia.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
emilia.keyPressed(e);
}
}
}
Emilia.java
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Emilia {
private String emilia = "emiliasprite.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public Emilia() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(emilia));
image = ii.getImage();
x = 40;
y = 60;
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = -1;
}
if (key == KeyEvent.VK_D) {
dx = 1;
}
if (key == KeyEvent.VK_W) {
dy = -1;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = 0;
}
if (key == KeyEvent.VK_D) {
dx = 0;
}
if (key == KeyEvent.VK_W) {
dy = 0;
}
}
}
ImageIcon.java - Line 205
this(location, location.toExternalForm());
Again, I'm beginner level so if you guys could explain it as you would to a newcomer to java (or any programming language for that matter)
Thanks for any help. - Niblexis
path of .png file:
C:\Users\Damon\workspace\TestGame\Resources\Sprites\Player
The .png file is in the player folder. I tried to run the program via the run button in Eclipse. At least, I think it's the run button because it's what showed me the errors in the first place.
Looks like the problem is in this line:
ImageIcon ii = new ImageIcon(this.getClass().getResource(emilia));
which means most likely that you haven't placed your .png file in the right place for Java to find it.
Could you post the exact path of the .png file on disk?
More specifically: a null pointer in this line of ImageIcon.java:
this(location, location.toExternalForm());
would imply that the URL location is null (causing an exception in the method call .toExternalForm(). If you look at the docs for Class.getResource() you will see it says:
Returns: A URL object or null if no resource with this name is found
which implies that Java can't find the resource in question.
For us to help, you will need to describe your runtime environment (are you running your program from .class files or in a .jar? at the command-line or in a debugger in Eclipse / Netbeans?) so we can help you figure out why the resource isn't being found.
You're effectively calling Emilia.class.getResource("emiliasprite.png") with Emilia.java in the default (root) package, which means that you need to tell your IDE / build process to copy this file into the root of the classpath. (in the same directory that Emilia.class ends up) Otherwise, Java has no idea where to find it.
If you want to place the resource somewhere else, you need to change the path accordingly, as well as the mechanism that copies the resource from the source directory to the appropriate place on the classpath.
See this stackoverflow answer: Java in Eclipse: Where do I put files on the filesystem that I want to load using getResource? (e.g. images for an ImageIcon)

Java IO can't read input file?

I have just started learning java and I've been working on this code for a moving object with keyboard input. I am now trying to add in a background, but it keeps erroring with:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at game.GameLoop.run(GameLoop.java:24)
at java.lang.Thread.run(Unknown Source)
The code I have in Game.java is:
package game;
import java.applet.*;
import java.awt.*;
public class Game extends GameLoop{
public void init(){
setSize(864,480);
Thread th = new Thread(this);
th.start();
offscreen = createImage(864,480);
d = offscreen.getGraphics();
addKeyListener(this);
}
public void paint(Graphics g){
d.clearRect(0, 0, 864, 480);
d.drawImage(background, 0, 0, this);
d.drawRect(x, y, 20, 20);
g.drawImage(offscreen, 0, 0, this);
}
public void update(Graphics g){
paint(g);
}
}
And here is my GameLoop.java:
package game;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class GameLoop extends Applet implements Runnable, KeyListener{
public int x, y;
public Image offscreen;
public Graphics d;
public boolean up, down, left, right;
public BufferedImage background;
public void run(){
x = 100;
y = 100;
try {
background = ImageIO.read(new File("background.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
while(true){
x = 100;
y = 100;
while(true){
if (left == true){
x-=4;
}
if (right == true){
x+=4;
}
if (up == true){
y-=4;
}
if (down == true){
y+=4;
}
if ( x <= 0 ){
x = 0;
}
if ( y <= 0 ){
y = 0;
}
if ( x >= 843 ){
x = 843;
}
if ( y >= 460 ){
y = 459;
}
repaint();
try{
Thread.sleep(20);
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
//#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 37){
left = true;
}
if(e.getKeyCode() == 38){
up = true;
}
if(e.getKeyCode() == 39){
right = true;
}
if(e.getKeyCode() == 40){
down = true;
}
}
//#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 37){
left = false;
}
if(e.getKeyCode() == 38){
up = false;
}
if(e.getKeyCode() == 39){
right = false;
}
if(e.getKeyCode() == 40){
down = false;
}
}
//#Override
public void keyTyped(KeyEvent e) {
}
}
Sorry about the editing I can't seem to get it all in the ``, and I will also fix the messy code, but do you guys have any ideas what is causing this error, there is a file in the src dir called background.png, it is very basic and made in MS paint, if that helps.
Thanks.
There are two places a simple, sand-boxed applet can obtain images.
Where
A loose file on the same server the applet was supplied from. E.G. This might be used for a sand-boxed 'image slideshow' where the image names are supplied in applet parameters.
A Jar on the run-time class-path of the applet. Best for resources which would not typically change (barring localized images, where it becomes more complicated). E.G. This might be used for button/menu icons, or BG images.
"background.png" strongly indicates the 2nd scenario - 'part of the app. itself'.
How to find
Both types of resources should identified by URL (do not try to establish a File as it will fail when the applet is deployed).
The way to obtain an URL for the 2nd case is something along the lines of:
URL urlToBG = this.getClass().getResource("/path/to/the/background.png");
..where /path/to/the/ might simply be /resources/ or /images/. It is the path within a Jar on the classpath, where the image can be found.
How to load
Most methods that will load a File are overloaded to accept an URL. This notably applies to ImageIO.read(URL).
While the Applet class has inbuilt methods to load images, I recommend sticking with ImageIO since it provides more comprehensive feed-back on failure.
Further tips
Tip 1
Thread.sleep(20);
Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeating tasks or a SwingWorker for long running tasks. See Concurrency in Swing for more details.
Tip 2
It is the third millennium, time to start using Swing instead of AWT. That would mean extending JApplet instead of Applet. Then you might shift the logic of painting into a JPanel that is double-buffered by default, and could be used in either the applet or a frame (or a window or a dialog..).
Tip 3
setSize(864,480);
The size of an applet is set in HTML, and the applet should accept whatever size it is assigned and work within that. Taking that into account, statements like:
d.clearRect(0, 0, 864, 480);
..should read more like:
d.clearRect(0, 0, getWidth(), getHeight());
#Patricia Shanahan Your comment actually helped me to solve the same problem.
I've used that code:
File here = new File(".");
try {
System.out.println(here.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and from there you can figure out the correct path to use.

Capturing image from webcam in java?

How can I continuously capture images from a webcam?
I want to experiment with object recognition (by maybe using java media framework).
I was thinking of creating two threads
one thread:
Node 1: capture live image
Node 2: save image as "1.jpg"
Node 3: wait 5 seconds
Node 4: repeat...
other thread:
Node 1: wait until image is captured
Node 2: using the "1.jpg" get colors
from every pixle
Node 3: save data in arrays
Node 4: repeat...
This JavaCV implementation works fine.
Code:
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.IplImage;
import java.io.File;
import static org.bytedeco.opencv.global.opencv_core.cvFlip;
import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;
public class Test implements Runnable {
final int INTERVAL = 100;///you may use interval
CanvasFrame canvas = new CanvasFrame("Web Cam");
public Test() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
public void run() {
new File("images").mkdir();
FrameGrabber grabber = new OpenCVFrameGrabber(0); // 1 for next camera
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
IplImage img;
int i = 0;
try {
grabber.start();
while (true) {
Frame frame = grabber.grab();
img = converter.convert(frame);
//the grabbed frame will be flipped, re-flip to make it right
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
//save
cvSaveImage("images" + File.separator + (i++) + "-aa.jpg", img);
canvas.showImage(converter.convert(img));
Thread.sleep(INTERVAL);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Test gs = new Test();
Thread th = new Thread(gs);
th.start();
}
}
There is also post on configuration for JavaCV
You can modify the code and be able to save the images in regular interval and do rest of the processing you want.
Some time ago I've created generic Java library which can be used to take pictures with a PC webcam. The API is very simple, not overfeatured, can work standalone, but also supports additional webcam drivers like OpenIMAJ, JMF, FMJ, LTI-CIVIL, etc, and some IP cameras.
Link to the project is https://github.com/sarxos/webcam-capture
Example code (take picture and save in test.jpg):
Webcam webcam = Webcam.getDefault();
webcam.open();
BufferedImage image = webcam.getImage();
ImageIO.write(image, "JPG", new File("test.jpg"));
It is also available in Maven Central Repository or as a separate ZIP which includes all required dependencies and 3rd party JARs.
JMyron is very simple for use.
http://webcamxtra.sourceforge.net/
myron = new JMyron();
myron.start(imgw, imgh);
myron.update();
int[] img = myron.image();
Here is a similar question with some - yet unaccepted - answers. One of them mentions FMJ as a java alternative to JMF.
This kind of goes off of gt_ebuddy's answer using JavaCV, but my video output is at a much higher quality then his answer. I've also added some other random improvements (such as closing down the program when ESC and CTRL+C are pressed, and making sure to close down the resources the program uses properly).
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class HighRes extends JComponent implements Runnable {
private static final long serialVersionUID = 1L;
private static CanvasFrame frame = new CanvasFrame("Web Cam");
private static boolean running = false;
private static int frameWidth = 800;
private static int frameHeight = 600;
private static OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
private static BufferedImage bufImg;
public HighRes()
{
// setup key bindings
ActionMap actionMap = frame.getRootPane().getActionMap();
InputMap inputMap = frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
for (Keys direction : Keys.values())
{
actionMap.put(direction.getText(), new KeyBinding(direction.getText()));
inputMap.put(direction.getKeyStroke(), direction.getText());
}
frame.getRootPane().setActionMap(actionMap);
frame.getRootPane().setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);
// setup window listener for close action
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
stop();
}
});
}
public static void main(String... args)
{
HighRes webcam = new HighRes();
webcam.start();
}
#Override
public void run()
{
try
{
grabber.setImageWidth(frameWidth);
grabber.setImageHeight(frameHeight);
grabber.start();
while (running)
{
final IplImage cvimg = grabber.grab();
if (cvimg != null)
{
// cvFlip(cvimg, cvimg, 1); // mirror
// show image on window
bufImg = cvimg.getBufferedImage();
frame.showImage(bufImg);
}
}
grabber.stop();
grabber.release();
frame.dispose();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void start()
{
new Thread(this).start();
running = true;
}
public void stop()
{
running = false;
}
private class KeyBinding extends AbstractAction {
private static final long serialVersionUID = 1L;
public KeyBinding(String text)
{
super(text);
putValue(ACTION_COMMAND_KEY, text);
}
#Override
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if (action.equals(Keys.ESCAPE.toString()) || action.equals(Keys.CTRLC.toString())) stop();
else System.out.println("Key Binding: " + action);
}
}
}
enum Keys
{
ESCAPE("Escape", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)),
CTRLC("Control-C", KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK)),
UP("Up", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)),
DOWN("Down", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)),
LEFT("Left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)),
RIGHT("Right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
private String text;
private KeyStroke keyStroke;
Keys(String text, KeyStroke keyStroke)
{
this.text = text;
this.keyStroke = keyStroke;
}
public String getText()
{
return text;
}
public KeyStroke getKeyStroke()
{
return keyStroke;
}
#Override
public String toString()
{
return text;
}
}
You can try Java Webcam SDK library also.
SDK demo applet is available at link.
I have used JMF on a videoconference application and it worked well on two laptops: one with integrated webcam and another with an old USB webcam. It requires JMF being installed and configured before-hand, but once you're done you can access the hardware via Java code fairly easily.
You can try Marvin Framework. It provides an interface to work with cameras. Moreover, it also provides a set of real-time video processing features, like object tracking and filtering.
Take a look!
Real-time Video Processing Demo:
http://www.youtube.com/watch?v=D5mBt0kRYvk
You can use the source below. Just save a frame using MarvinImageIO.saveImage() every 5 second.
Webcam video demo:
public class SimpleVideoTest extends JFrame implements Runnable{
private MarvinVideoInterface videoAdapter;
private MarvinImage image;
private MarvinImagePanel videoPanel;
public SimpleVideoTest(){
super("Simple Video Test");
videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
videoPanel = new MarvinImagePanel();
add(videoPanel);
new Thread(this).start();
setSize(800,600);
setVisible(true);
}
#Override
public void run() {
while(true){
// Request a video frame and set into the VideoPanel
image = videoAdapter.getFrame();
videoPanel.setImage(image);
}
}
public static void main(String[] args) {
SimpleVideoTest t = new SimpleVideoTest();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
For those who just want to take a single picture:
WebcamPicture.java
public class WebcamPicture {
public static void main(String[] args) {
try{
MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
MarvinImage image = videoAdapter.getFrame();
MarvinImageIO.saveImage(image, "./res/webcam_picture.jpg");
} catch(MarvinVideoInterfaceException e){
e.printStackTrace();
}
}
}
I used Webcam Capture API. You can download it from here
webcam = Webcam.getDefault();
webcam.open();
if (webcam.isOpen()) { //if web cam open
BufferedImage image = webcam.getImage();
JLabel imageLbl = new JLabel();
imageLbl.setSize(640, 480); //show captured image
imageLbl.setIcon(new ImageIcon(image));
int showConfirmDialog = JOptionPane.showConfirmDialog(null, imageLbl, "Image Viewer", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(""));
if (showConfirmDialog == JOptionPane.YES_OPTION) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save Image");
chooser.setFileFilter(new FileNameExtensionFilter("IMAGES ONLY", "png", "jpeg", "jpg")); //this file extentions are shown
int showSaveDialog = chooser.showSaveDialog(this);
if (showSaveDialog == 0) { //if pressed 'Save' button
String filePath = chooser.getCurrentDirectory().toString().replace("\\", "/");
String fileName = chooser.getSelectedFile().getName(); //get user entered file name to save
ImageIO.write(image, "PNG", new File(filePath + "/" + fileName + ".png"));
}
}
}
http://grack.com/downloads/school/enel619.10/report/java_media_framework.html
Using the Player with Swing
The Player can be easily used in a Swing application as well. The following code creates a Swing-based TV capture program with the video output displayed in the entire window:
import javax.media.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.event.*;
public class JMFTest extends JFrame {
Player _player;
JMFTest() {
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
_player.stop();
_player.deallocate();
_player.close();
System.exit( 0 );
}
});
setExtent( 0, 0, 320, 260 );
JPanel panel = (JPanel)getContentPane();
panel.setLayout( new BorderLayout() );
String mediaFile = "vfw://1";
try {
MediaLocator mlr = new MediaLocator( mediaFile );
_player = Manager.createRealizedPlayer( mlr );
if (_player.getVisualComponent() != null)
panel.add("Center", _player.getVisualComponent());
if (_player.getControlPanelComponent() != null)
panel.add("South", _player.getControlPanelComponent());
}
catch (Exception e) {
System.err.println( "Got exception " + e );
}
}
public static void main(String[] args) {
JMFTest jmfTest = new JMFTest();
jmfTest.show();
}
}
Java usually doesn't like accessing hardware, so you will need a driver program of some sort, as goldenmean said. I've done this on my laptop by finding a command line program that snaps a picture. Then it's the same as goldenmean explained; you run the command line program from your java program in the takepicture() routine, and the rest of your code runs the same.
Except for the part about reading pixel values into an array, you might be better served by saving the file to BMP, which is nearly that format already, then using the standard java image libraries on it.
Using a command line program adds a dependency to your program and makes it less portable, but so was the webcam, right?
I believe the web-cam application software which comes along with the web-cam, or you native windows webcam software can be run in a batch script(windows/dos script) after turning the web cam on(i.e. if it needs an external power supply). In the bacth script , u can add appropriate delay to capture after certain time period. And keep executing the capture command in loop.
I guess this should be possible
-AD
There's a pretty nice interface for this in processing, which is kind of a pidgin java designed for graphics. It gets used in some image recognition work, such as that link.
Depending on what you need out of it, you might be able to load the video library that's used there in java, or if you're just playing around with it you might be able to get by using processing itself.
FMJ can do this, as can the supporting library it uses, LTI-CIVIL. Both are on sourceforge.
Recommand using FMJ for multimedia relatived java app.
Try using JMyron How To Use Webcam Using Java. I think using JMyron is the easiest way to access a webcam using java. I tried to use it with a 64-bit processor, but it gave me an error. It worked just fine on a 32-bit processor, though.

Categories