I am trying to get and display an video stream from a IP camera. I found some sample code here:http://answers.opencv.org/question/24012/reading-video-stream-from-ip-camera-in-opencv-java/
But it is not working for me. my code works when I use my internal webcam, but when I switch the camera to the IP, it does not work. I have no idea why. Can someone please help me?
Here is my code:
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
public class openCVTest
{
public openCVTest()
{
// TODO Auto-generated constructor stub
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException
{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//VideoCapture camera = new VideoCapture("http://192.168.0.7/image.jpg");
VideoCapture camera = new VideoCapture(0);
if (camera.isOpened())
{
System.out.println("Video is captured");
}
else
{
System.out.println("");
}
videoCamera cam = new videoCamera(camera);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(cam);
frame.setSize(800,800);
frame.setVisible(true);
while(camera.isOpened())
{
cam.repaint();
}
}
}
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.core.*;
#SuppressWarnings("serial")
public class videoCamera extends JPanel
{
VideoCapture camera;
public videoCamera(VideoCapture cam)
{
camera = cam;
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
}
public BufferedImage Mat2BufferedImage(Mat m)
{
int type = BufferedImage.TYPE_BYTE_GRAY;
if (m.channels() > 1)
{
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels() * m.cols() * m.rows();
byte[] b = new byte[bufferSize];
m.get(0, 0, b); // get all the pixels
BufferedImage img = new BufferedImage(m.cols(), m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return img;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Mat mat = new Mat();
if( camera.read(mat))
{
System.out.print("IMAGE");
}
BufferedImage image = Mat2BufferedImage(mat);
//Mat gray = turnGray(mat);
//MatOfRect objects = new MatOfRect();
//CascadeClassifier cas = new CascadeClassifier();
//cas.detectMultiScale(gray,objects);
//Mat thresh = threash( gray);
//BufferedImage image = Mat2BufferedImage(thresh);
g.drawImage(image,10,10,image.getWidth(),image.getHeight(), null);
}
public Mat turnGray( Mat img)
{
Mat mat1 = new Mat();
Imgproc.cvtColor(img, mat1, Imgproc.COLOR_RGB2GRAY);
return mat1;
}
public Mat threash(Mat img)
{
Mat threshed = new Mat();
int SENSITIVITY_VALUE = 100;
Imgproc.threshold(img, threshed, SENSITIVITY_VALUE,255,Imgproc.THRESH_BINARY);
return threshed;
}
}
Thank you for the help. I was able to use what you said to find the proper IP address (http://192.168.0.6/VIDEO.CGI) (yes, I know the 7 became a 6, its a different camera) to get a video in my browser. but I am still get the following error.
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Width (0) and height (0) must be > 0
at java.awt.image.SampleModel.<init>(Unknown Source)
at java.awt.image.ComponentSampleModel.<init>(Unknown Source)
at java.awt.image.PixelInterleavedSampleModel.<init>(Unknown Source)
at java.awt.image.Raster.createInterleavedRaster(Unknown Source)
at java.awt.image.Raster.createInterleavedRaster(Unknown Source)
at java.awt.image.Raster.createInterleavedRaster(Unknown Source)
at java.awt.image.ComponentColorModel.createCompatibleWritableRaster(Unknown Source)
at java.awt.image.BufferedImage.<init>(Unknown Source)
at videoCamera.Mat2BufferedImage(videoCamera.java:54)
at videoCamera.paintComponent(videoCamera.java:74)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JLayeredPane.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.BufferStrategyPaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
at java.awt.Container.paint(Unknown Source)
at java.awt.Window.paint(Unknown Source)
at javax.swing.RepaintManager$3.run(Unknown Source)
at javax.swing.RepaintManager$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1100(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I think it is because VideoCapture is not grabbing the frame correctly.
This is the camera I am trying to use
http://www.trendnet.com/products/proddetail.asp?prod=150_TV-IP100W-N
.jpg refers to a single image file, while .mjpg gives access to the video stream. It's important to define the IP and the PORT used to connect.
Depending on the device you have and the settings defined in the web interface of the camera, the URL is going to be different:
VideoCapture camera = new VideoCapture("http://192.168.0.7:8080/?dummy=param.mjpg");
VideoCapture camera = new VideoCapture("http://192.168.0.7:8080/mjpeg.cgi");
VideoCapture camera = new VideoCapture("http://192.168.0.7:8080/mjpg/mjpeg.cgi");
VideoCapture camera = new VideoCapture("http://192.168.0.7:8080/video.mjpeg");
VideoCapture camera = new VideoCapture("http://192.168.0.7:8080/video.cgi?.mjpg");
When you access a valid URL via browser it should display the video stream. Once you find the address that works, simply pass it to VideoCapture constructor. In this examples I showed how to access the stream via HTTP, but the RTSP protocol is also supported.
After 3 to 4 weeks of hardwork,I found a 100% working solution for this
First of All you have to load the ffmpeg's dll file Dynamically i-e Using
System.loadLibrary("[NAME OF YOUR DLL FILE]")
You can find the required dll file in **opencv/build/x64/vc11/bin**
The name of DLL in my case is "opencv_ffmpeg2413_64.dll"
copy the file to default path of the Project and use
System.loadLibrary("opencv_ffmpeg2413_64");//You May have different File Name Depending on the Version of OpenCV Installed on your Computer
Then You can Simply use
VideoCapture ipcamera = new VideoCapture("[RTSP URL OF THE IP Camera]")//I used this Demo Link (rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov)
Related
So I'm creating a program that gets the swagger doc.json, extracts all the REST Apis then shows them in an Accordion: the problem is that the Accordion won't work for me because TitledPanes are added dynamically: i.e: for each Rest API endpoint extracted out of the JSON file a new TitledPane will show up.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.parser.SwaggerParser;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class GroupOfTitledPane extends Application {
JFrame frame;
JTextField t1;
JButton btn;
int i;
#Override
public void start(final Stage stage) {
frame=new JFrame();
frame.setLayout(null);
frame.setSize(400,250);
frame. setLocation(500,300);
t1=new JTextField();
t1.setBounds(60,40,270,30);
frame.add(t1);
btn=new JButton("SUBMIT");
btn.setBounds(140,90,100,30);
frame.add(btn);
frame.setVisible(true);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn)
{
String input=t1.getText();
if(input.isEmpty() || input.equals(" "))
{
JOptionPane.showMessageDialog(null,"Veuillez saisir l'adresse de l'URL");
}
else{
URL urldoc = null;
try {
urldoc = new URL(input);
}
catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String url = new String("https://"+urldoc.getAuthority()+"/v2/swagger.json");
System.out.println(url);
Swagger swagger = new SwaggerParser().read(url);
Map<String, Path> paths = swagger.getPaths();
// Create Root Pane.
VBox root = new VBox();
root.setPadding(new Insets(20, 10, 10, 10));
for (Map.Entry<String, Path> p : paths.entrySet()) {
Path path = p.getValue();
Map<HttpMethod, Operation> operations = path.getOperationMap();
for (java.util.Map.Entry<HttpMethod, Operation> o : operations.entrySet()) {
System.out.println("===");
System.out.println("PATH:" + p.getKey());
System.out.println("Http method:" + o.getKey());
System.out.println("Summary:" + o.getValue().getSummary());
System.out.println("Parameters number: " + o.getValue().getParameters().size());
for (Parameter parameter : o.getValue().getParameters()) {
System.out.println(" - " + parameter.getName());
}
System.out.println("Responses:");
for (Map.Entry<String, Response> r : o.getValue().getResponses().entrySet()) {
System.out.println(" - " + r.getKey() + ": " + r.getValue().getDescription());
}
// Create First TitledPane.
TitledPane firstTitledPane = new TitledPane();
firstTitledPane.setText((o.getKey()).toString() + ":" + (p.getKey()).toString());
VBox content1 = new VBox();
content1.getChildren().add(new Label("Java Swing Tutorial"));
content1.getChildren().add(new Label("JavaFx Tutorial"));
content1.getChildren().add(new Label("Java IO Tutorial"));
firstTitledPane.setContent(content1);
root.getChildren().addAll(firstTitledPane);
Scene scene = new Scene(root, 300, 200);
stage.setScene(scene);
stage.show();
}
}
}
}
}
});
}
public static void main(String[] args) {
Application.launch(args);
}
}
And here is the error:
https://petstore.swagger.io/v2/swagger.json 0 [AWT-EventQueue-0] INFO io.swagger.parser.Swagger20Parser - reading from https://petstore.swagger.io/v2/swagger.json
=== PATH:/pet/{petId} Http method:GET Summary:Find pet by ID Parameters number: 1
- petId Responses:
- 200: successful operation
- 400: Invalid ID supplied
- 404: Pet not found Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException:
Not on FX application thread; currentThread = AWT-EventQueue-0
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:279)
atcom.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:444) at javafx.stage.Window.setShowing(Window.java:939) at javafx.stage.Window.show(Window.java:955) at javafx.stage.Stage.show(Stage.java:259) at GroupOfTitledPane$1.actionPerformed(GroupOfTitledPane.java:102) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am creating a 'Troll' like application to use in a YouTube video, and I want a JFrame to jump around the screen every 1/2 second.
Heres my code:
package troll1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class troll extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
troll w1 = new troll();
w1.setVisible(true);
w1.setSize(500,500);
}
public Random ran;
public int random;
public troll w1;
public Timer t;
public troll() {
Timer t = new Timer(500, this);
t.start();
}
#Override
public void actionPerformed(ActionEvent arg0) {
Random ran = new Random();
for(int counter=1; counter<=1;counter++) {
int random = 1+ran.nextInt(500);
w1.setLocation(random, random);
}
}
}
The problem is, when I run this code, I get a error saying,
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at troll1.troll.actionPerformed(troll.java:37)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
Also, once I get this error gone, I will make it so the JFrame jumps around the entire screen, not just 500,500 and below.
the w1 variable is always null is never valorized. you can use this in actionPerformed to make it work this way
#Override
public void actionPerformed(ActionEvent arg0) {
Random ran = new Random();
for(int counter=1; counter<=1;counter++) {
int random = 1+ran.nextInt(500);
this.setLocation(random, random);
}
}
I have a java application where when the user presses a button, I want it to open another different application in a new window. However, the application is a programmed one in Eclipse, not one downloaded onto my computer. I have tried various things such as running threads, but to no avail. Here is the section of the class where the user pushes the button:
JButton LiveFeed = new JButton("Live Feed");
final JPanel jsr3 = new JPanel();
jsr3.add(LiveFeed);
LiveFeed.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
new KinectViewer();
}
});
jsr3.setVisible(true);
And here is the class that I am trying to open seperate from the main application:
package skeleton;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import edu.ufl.digitalworlds.gui.DWApp;
#SuppressWarnings("serial")
public class KinectViewer extends DWApp implements ChangeListener
{
Kinect myKinect;
ViewerPanel3D main_panel;
JSlider elevation_angle;
JCheckBox near_mode;
JCheckBox seated_skeleton;
JCheckBox track_skeleton;
JButton turn_off;
JComboBox depth_resolution;
JComboBox video_resolution;
JCheckBox show_video;
JCheckBox mask_players;
JLabel accelerometer;
public void GUIsetup(JPanel p_root) {
setLoadingProgress("Intitializing Kinect...",20);
myKinect=new Kinect();
if(myKinect.start(true,Kinect.NUI_IMAGE_RESOLUTION_320x240,Kinect.NUI_IMAGE_RESOLUTION_640x480)==0)
{
DWApp.showErrorDialog("ERROR", "<html><center><br>ERROR: The Kinect device could not be initialized.<br><br>1. Check if the Microsoft's Kinect SDK was succesfully installed on this computer.<br> 2. Check if the Kinect is plugged into a power outlet.<br>3. Check if the Kinect is connected to a USB port of this computer.</center>");
//System.exit(0);
}
myKinect.computeUV(true);
near_mode=new JCheckBox("Near mode");
near_mode.addActionListener(this);
seated_skeleton=new JCheckBox("Seated skeleton");
seated_skeleton.addActionListener(this);
elevation_angle=new JSlider();
elevation_angle.setMinimum(-27);
elevation_angle.setMaximum(27);
elevation_angle.setValue((int)myKinect.getElevationAngle());
elevation_angle.setToolTipText("Elevation Angle ("+elevation_angle.getValue()+" degrees)");
elevation_angle.addChangeListener(this);
turn_off=new JButton("Turn off");
turn_off.addActionListener(this);
depth_resolution=new JComboBox();
depth_resolution.addItem("80x60");
depth_resolution.addItem("320x240");
depth_resolution.addItem("640x480");
depth_resolution.setSelectedIndex(1);
depth_resolution.addActionListener(this);
video_resolution=new JComboBox();
video_resolution.addItem("640x480");
video_resolution.addItem("1280x960");
video_resolution.setSelectedIndex(0);
video_resolution.addActionListener(this);
track_skeleton=new JCheckBox("Track Skeletons");
track_skeleton.setSelected(true);
track_skeleton.addActionListener(this);
show_video=new JCheckBox("Show video");
show_video.setSelected(true);
show_video.addActionListener(this);
mask_players=new JCheckBox("Mask Players");
mask_players.setSelected(false);
mask_players.addActionListener(this);
JPanel controls=new JPanel(new GridLayout(0,6));
controls.add(new JLabel("Depth Stream:"));
controls.add(depth_resolution);
controls.add(near_mode);
controls.add(new JLabel("Video Stream:"));
controls.add(video_resolution);
controls.add(show_video);
controls.add(new JLabel("Skeleton Stream:"));
controls.add(track_skeleton);
controls.add(seated_skeleton);
controls.add(mask_players);
accelerometer=new JLabel("0,0,0");
controls.add(accelerometer);
controls.add(elevation_angle);
//controls.add(turn_off);
setLoadingProgress("Intitializing OpenGL...",60);
main_panel=new ViewerPanel3D();
myKinect.setViewer(main_panel);
myKinect.setLabel(accelerometer);
p_root.add(main_panel, BorderLayout.CENTER);
p_root.add(controls, BorderLayout.SOUTH);
System.out.print("GUIsetup");
}
public void GUIclosing()
{
myKinect.stop();
}
private void resetKinect()
{
if(turn_off.getText().compareTo("Turn on")==0) return;
myKinect.stop();
int depth_res=Kinect.NUI_IMAGE_RESOLUTION_INVALID;
if(depth_resolution.getSelectedIndex()==0) depth_res=Kinect.NUI_IMAGE_RESOLUTION_80x60;
else if(depth_resolution.getSelectedIndex()==1) depth_res=Kinect.NUI_IMAGE_RESOLUTION_320x240;
else if(depth_resolution.getSelectedIndex()==2) depth_res=Kinect.NUI_IMAGE_RESOLUTION_640x480;
int video_res=Kinect.NUI_IMAGE_RESOLUTION_INVALID;
if(video_resolution.getSelectedIndex()==0) video_res=Kinect.NUI_IMAGE_RESOLUTION_640x480;
else if(video_resolution.getSelectedIndex()==1) video_res=Kinect.NUI_IMAGE_RESOLUTION_1280x960;
myKinect.start(track_skeleton.isSelected(),depth_res,video_res);
myKinect.computeUV(true);
if(seated_skeleton.isSelected())myKinect.startSkeletonTracking(true);
if(near_mode.isSelected()) myKinect.setNearMode(true);
}
public static void main(String args[]) {
createMainFrame("Kinect Viewer App");
app=new KinectViewer();
setFrameSize(730,570,null);
System.out.print("main");
}
#Override
public void GUIactionPerformed(ActionEvent e)
{
if(e.getSource()==near_mode)
{
if(near_mode.isSelected()) myKinect.setNearMode(true);
else myKinect.setNearMode(false);
}
else if(e.getSource()==seated_skeleton)
{
if(seated_skeleton.isSelected()) myKinect.startSkeletonTracking(true);
else myKinect.startSkeletonTracking(false);
}
else if(e.getSource()==track_skeleton)
{
if(track_skeleton.isSelected())
{
if(seated_skeleton.isSelected()) myKinect.startSkeletonTracking(true);
else myKinect.startSkeletonTracking(false);
}
else myKinect.stopSkeletonTracking();
}
else if(e.getSource()==turn_off)
{
if(turn_off.getText().compareTo("Turn off")==0)
{
myKinect.stop();
turn_off.setText("Turn on");
}
else
{
turn_off.setText("Turn off");
resetKinect();
}
}
else if(e.getSource()==depth_resolution)
{
resetKinect();
}
else if(e.getSource()==video_resolution)
{
resetKinect();
}
else if(e.getSource()==show_video)
{
main_panel.setShowVideo(show_video.isSelected());
}
else if(e.getSource()==mask_players)
{
myKinect.maskPlayers(mask_players.isSelected());
}
}
#Override
public void stateChanged(ChangeEvent e) {
if(e.getSource()==elevation_angle)
{
if(!elevation_angle.getValueIsAdjusting())
{
myKinect.setElevationAngle(elevation_angle.getValue());
elevation_angle.setToolTipText("Elevation Angle ("+elevation_angle.getValue()+" degrees)");
}
}
}
}
However, when I run this, I get this following NPE:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at edu.ufl.digitalworlds.gui.DWApp.<init>(DWApp.java:173)
at skeleton.KinectViewer.<init>(KinectViewer.java:53)
at skeleton.TestSplitPanels$1.actionPerformed(TestSplitPanels.java:66)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Why is this?
Please note that KinectViewer can be opened as its own java application and works just fine by itself and if you are wondering about the DWApp, the DWApp class is a class in the edu.ufl.digitalworlds.gui package in the ufdw.jar (downloaded via this site posted above). It has two types of its class: one for a java application (which I'm using) and one for an applet. Inside the class are a bunch of methods seeming to deal with application look and processes (word sizing, formating, error dialogs, ect.). During setting everything up, I imported a project from git, and used a uri of "research.dwi.ufl.edu/j4kdemo".
I'm trying to do collision I thought I got it but apparently not so when I ran my game I got an error.. Which is really annoying. So I've come here to get some help :D hopefully :P
Anyway I kept on getting this error
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.shiny21.graphics.GFX.step(GFX.java:37)
at com.shiny21.graphics.GFX.actionPerformed(GFX.java:65)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I don't really understand errors yet but heres the code GFX:
package com.shiny21.graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
import com.shiny21.framework.Collision;
import com.shiny21.players.PlayerB;
import com.shiny21.players.PlayerR;
public class GFX extends JPanel implements ActionListener{
PlayerR red;
PlayerB blue;
Collision col;
public GFX(){
red = new PlayerR(getX(), getY());
blue = new PlayerB(getX(), getY());
this.setFocusable(true);
this.requestFocus();
setBackground(Color.BLACK);
Timer timer = new Timer(1000 / 60, this);
timer.start();
}
public void step(){
col.CollisionStep();
red.step();
blue.step();
//System.out.println("");
}
public void paintComponent(Graphics g){
super.paintComponent(g);
//RED
g.setColor(Color.RED);
g.fillRect(red.getX(), red.getY(), 8, 8);
g.setColor(Color.WHITE);
g.drawRect(red.getX()+20 - red.getSightW(), red.getY()+20 - red.getSightH(), red.getSightW(), red.getSightH());
//BLUE
g.setColor(Color.BLUE);
g.fillRect(blue.getX(), blue.getY(), 8, 8);
g.setColor(Color.GREEN);
g.drawRect(blue.getX()+20 - blue.getSightW(), blue.getY()+20 - blue.getSightH(), blue.getSightW(), blue.getSightH());
}
public void actionPerformed(ActionEvent ae) {
step();
repaint();
}
}
So that was that heres the Collision code:
package com.shiny21.framework;
import java.awt.Rectangle;
import com.shiny21.players.PlayerB;
import com.shiny21.players.PlayerR;
public class Collision {
PlayerB blue;
PlayerR red;
public Collision(){
CollisionStep();
}
public void CollisionStep(){
Rectangle r1 = blue.getBounds();
Rectangle r2 = red.getBounds();
if(r1.intersects(r2)){
blue.setDX(-1);
red.setDX(1);
}
}
}
EDIT 1:
I now get this error
Exception in thread "main" java.lang.NullPointerException
at com.shiny21.framework.Collision.<init>(Collision.java:14)
at com.shiny21.graphics.GFX.<init>(GFX.java:25)
at com.shiny21.framework.Game.main(Game.java:18)
I then added this to the Collision class:
blue = new PlayerB(blue.getX(), blue.getY());
red = new PlayerR(red.getX(), red.getY());
Your field col is null and never set. This line col.CollisionStep();
I am making a small hobby game, I have a couple of classes so far. There are two classes that I am having some issues with, the classes in question are listed below.
Screen.Java
package geisst.flat;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Screen extends JFrame {
public int x = 100;
public int y = 100;
public Screen() {
this.setSize(400, 400);
this.setTitle("Flat Game");
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
addKeyListener(new KeyListen());
}
public void paint(Graphics g) {
BufferedImage mainImage = null;
try {
mainImage = ImageIO.read(new File("res/test.gif"));
} catch(IOException e) {
}
g.drawImage(mainImage, x, y, null);
repaint();
}
}
And KeyListen.Java
package geisst.flat;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyListen extends KeyAdapter {
Screen screen;
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT) {
screen.x += 3;
}
}
}
KeyListen is supposed to move the mainImage's x position up by 3 pixels, but I recieve the following error.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at geisst.flat.KeyListen.keyPressed(KeyListen.java:15)
at java.awt.Component.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Window.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Do you guy's and gal's have any idea why this would be happening? It's probably something really obvious :P
Thanks in advance,
GeissT
You are never initializing the value of screen.
What you can do is something like this:
In the KeyListener Class
public KeyListen (Screen screen) {
this.screen = screen;
}
and in the Screen Class:
addKeyListener(new KeyListen(this));
You never initialize screen, so it is null, and yet you use it's properties:
screen.x += 3;
You should pass a reference to the Screen object to the listener, or by calling getSource:
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT) {
if (e.getSource() instanceof Screen)
((Screen)e.getSource()).x += 3;
}
}
1) not good idea paint directly to the JFrame, put there JPanel, JComponent or JLabel
2) for Swing JComponents is there paintComponent instead of paint, paint is correct method for painting to the RootPane or GlassPane (derived Component from JFrame)
3) use KeyBindings rather than KeyListener, because KeyListener doesn't works without Focus in the Window, not good idea to setFocusable to the ContentPane
4) use JComponent for Custom Painting or JLabel with Icon
5) example for KeyBindings here