0

My basket returns error messages when I try to move it. keylistener prints out keys like usual and I looked for usual errors but I always get the same error message during the run.

keyPressed 39
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at view.DrawingPanel.right(DrawingPanel.java:65)
    at view.GameUI.keyPressed(GameUI.java:74)
    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$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)
keyPressed 37
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at view.DrawingPanel.left(DrawingPanel.java:60)
    at view.GameUI.keyPressed(GameUI.java:71)
    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$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)

the indicated error lines are for basket.setMoveL(true); in left & right in DrawingPanel and panel.left(); & right respectively

Here is my code for GameUI

package view;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Color;

public class GameUI extends JFrame implements KeyListener{

    private JPanel contentPane;
    private DrawingPanel panel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GameUI frame = new GameUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public GameUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 600, 400);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        panel = new DrawingPanel();
        panel.setBackground(Color.BLACK);
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addComponent(panel, GroupLayout.DEFAULT_SIZE, 574, Short.MAX_VALUE)
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addComponent(panel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
        );
        contentPane.setLayout(gl_contentPane);
        addKeyListener(this);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        // show keycode of pressed key:
         int k = e.getKeyCode();
        System.out.println("keyPressed " + k);

        //call direction left & right
        switch(k) {
        case 37:
            panel.left();
            break;
        case 39:
            panel.right();
            break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

}

And my code for the Drawing Panel

package view;

import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.Timer;

import model.ControlElement;
import model.DrawingObject;

public class DrawingPanel extends JPanel {

    private ArrayList<DrawingObject> gameElements;

    private ControlElement basket;
    private ControlElement launcher;
    private Timer t;

    public DrawingPanel() {
        super();
        // within constructor create a list of Game elements that are drawingObjects
        gameElements = new ArrayList<DrawingObject>();

        //initialize repainting 
        t = new Timer(20, (e) -> repaint() );
        t.start();
    }

    @Override   
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // paintComponent method
        if (basket == null) { //no basket is there yet so make one
            newBasket();
        }
        if (launcher == null) { //no launcher is there yet so make one
            newLauncher();
        }


        for (int i = gameElements.size()-1; i >= 0; i-- ) { // draw all game Elements
            gameElements.get(i).paintComponent(g);
        }
    }


    private void newBasket(){ //making a basket
        ControlElement basket = new ControlElement("basket.png", this, getWidth() / 2, getHeight() - 25);
        gameElements.add(basket);
    }

    private void newLauncher(){ // making a launcher
        ControlElement launcher = new ControlElement("launcher.png", this, 5, getHeight() - 55);
        gameElements.add(launcher);
    }


    public void left() {
        basket.setMoveL(true);
        basket.move();
    }

    public void right() {
        basket.setMoveL(false);
        basket.move();
    }
}

Thank you for your help

Share a link to this question (includes your user id)
| edit | | close | delete |
0

in the method newBasket() and newLauncher() you have 'ControlElement' in front of the variable:

private void newBasket(){ //making a basket
    ControlElement basket = new ControlElement("basket.png", this, getWidth() / 2, getHeight() - 25);
    gameElements.add(basket);
}

That can be deleted since it is a class variable declared at the top, so the program already knows what basket is. Like this:

private void newBasket(){ //making a basket
    basket = new ControlElement("basket.png", this, getWidth() / 2, getHeight() - 25);
    gameElements.add(basket);
}
Share a link to this answer (includes your user id)
| edit | | delete |

Your Answer

  • Links
  • Images
  • Styling/Headers
  • Lists
  • Blockquotes
  • Code
  • HTML
  • Advanced help

Images are exactly like links, but they have an exclamation point in front of them:

![a busy cat](https://cdn.sstatic.net/Sites/stackoverflow/Img/error-lolcat-problemz.jpg)
![two muppets][1]

 [1]: https://i.imgur.com/I5DFV.jpg "tooltip"

The word in square brackets is the alt text, which gets displayed if the browser can't show the image. Be sure to include meaningful alt text for screen-reading software.

Be sure to use text styling sparingly; only where it helps readability.

*This is italicized*, and so
is _this_.

**This is bold**, just like __this__.

You can ***combine*** them
if you ___really have to___.

To break your text into sections, you can use headers:

A Large Header
==============

Smaller Subheader
-----------------

Use hash marks if you need several levels of headers:

# Header 1 #
## Header 2 ##
### Header 3 ###

Both bulleted and numbered lists are possible:

- Use a minus sign for a bullet
+ Or plus sign
* Or an asterisk

1. Numbered lists are easy
2. Markdown keeps track of
   the numbers for you
7. So this will be item 3.
1. Lists in a list item:
    - Indented four spaces.
        * indented eight spaces.
    - Four spaces again.
2.  You can have multiple
    paragraphs in a list items.
 
    Just be sure to indent.
> Create a blockquote by
> prepending “>” to each line.
>
> Other formatting also works here, e.g.
>
> 1. Lists or
> 2. Headings:
>
> ## Quoted Heading ##

You can even put blockquotes in blockquotes:

> A standard blockquote is indented
> > A nested blockquote is indented more
> > > > You can nest to any depth.

To create code blocks or other preformatted text, indent by four spaces or surround with groups of backticks:

    This will be displayed in a monospaced font. The first four spaces
    will be stripped off, but all other whitespace will be preserved.

```
Markdown and HTML are turned off in code blocks:
<i>This is not italic</i>, and [this is not a link](https://example.com)
```

To create not a block, but an inline code span, use backticks:

The `$` character is just a shortcut for `window.jQuery`.

If you want to have a preformatted block within a list, indent by eight spaces:

1. This is normal text.
2. So is this, but now follows a code block:
 
        Skip a line and indent eight spaces.
        That's four spaces for the list
        and four to trigger the code block.

If you need to do something that Markdown can't handle, use HTML. Note that we only support a very strict subset of HTML!

Strikethrough humor is <strike>funny</strike>.

Markdown is smart enough not to mangle your span-level HTML:

<b>Markdown works *fine* in here.</b>

Block-level HTML elements have a few restrictions:

  1. They must be separated from surrounding text by blank lines.
  2. The begin and end tags of the outermost block element must not be indented.
  3. Markdown can't be used within HTML blocks.

<pre>
    You can <em>not</em> use Markdown in here.
</pre>

Not the answer you're looking for? Browse other questions tagged or ask your own question.