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);
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to get the timer working to move the ball. It just isn't working. I am getting alot of errors which i don't yet understand
Can someone tell me what i am doing wrong.
Here is the error that i got.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Paneel$TimerHandler.actionPerformed(Paneel.java:30)
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)
at java.awt.EventDispatchThread.run(Unknown Source)
Thanks in advance.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Paneel extends JPanel
{
private int height, width;
private boolean moveLeft, moveRight, moveUp, moveDown;
private Timer timer;
private Ball ball;
public Paneel()
{
TimerHandler timerHandler = new TimerHandler();
timer = new Timer(20, timerHandler);
timer.start();
}
public void paintComponent(Graphics pen)
{
super.paintComponent(pen);
ball = new Ball((double)getWidth(), (double)getHeight());
ball.drawBall(pen);
}
class TimerHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
ball.moveDown();
repaint();
}
}
}
You are creating a new Ball object during each paint
ball = new Ball((double)getWidth(), (double)getHeight());
That means that the ball reference is null up until the first paint call.
ball.moveDown(); // ball here could be null
I recommend defining ball in the constructor for now. I'll need to see the source of the Ball class before I can figure out how to set its size correctly.
public Paneel()
{
ball = new Ball(0, 0);
TimerHandler timerHandler = new TimerHandler();
timer = new Timer(20, timerHandler);
timer.start();
}
This question already has answers here:
how does a swing timer work?
(3 answers)
Closed 7 years ago.
I am trying to create a flashing circle. I have got to the point where it changed once and then it throws and error Exception in thread "AWT-EventQueue-0
i have no idea why. can you help me? This is my code:
public class Final {
private static JPanel contentPane;
private static int cnt = 0;
private static int counter =0;
private static Color[] colours = {
Color.ORANGE,
Color.GRAY
};
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(400, 525);
frame.setLocationByPlatform(true);
frame.setVisible(true);
ActionListener actListner = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (cnt == (colours.length)) {
cnt = 0;
}
frame.setBackground(colours[cnt++]);
counter = cnt;
System.out.println("Counter = "+cnt);
}
};
contentPane = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(colours[counter]);
g.fillOval(160, 70, 50, 50);
}
};
frame.add(contentPane);
Timer timer = new Timer(500, actListner);
timer.start();
}
}
The full exception:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2
at Final$2.paintComponent(Final.java:56)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.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$1300(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$400(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)
You're incrementing your counter after checking its bounds, and then using it. Don't do that as that's the wrong order of things. Increment first, next check bounds and reset to 0 if need be, and only then use it.
// increment first, cnt++;, but not inline as you're doing it
cnt++;
cnt %= colours.length; // mod it to make it 0 if greater than length
myColor = colours[cnt]; // then use it
repaint();
Simply change
if (cnt == (colours.length)){
to
if (cnt == (colours.length-1)){
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