0

I'm making a basic turtle type program where you enter a command and a line is drawn.

My issue is the program crashes every time I try to draw a line. I've tried a few things but it crashes once the command "penup" is input.

I have this error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GUI.GraphicalInterface$2.actionPerformed(GraphicalInterface.java:161)
at javax.swing.JTextField.fireActionPerformed(Unknown Source)
at javax.swing.JTextField.postActionEvent(Unknown Source)
at javax.swing.JTextField$NotifyAction.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(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.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)

#GraphicalInterface class

package GUI;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;


import javax.swing.*;


import GUI.Dialog;


import java.util.Scanner;






public class GraphicalInterface extends JFrame implements ActionListener{



public static BufferedImage image; 

private final static Color BACKGROUND_COL = Color.DARK_GRAY;

public void paint(Graphics g) {

    // render the image on the panel.
    g.drawImage(image, 0, 0, null);
}

public void drawLine(Color color, int x1, int y1, int x2, int y2) {

    Graphics g = image.getGraphics();

    g.setColor(color);

    g.drawLine(0, 10, 0, 0);
}




    public void paintComponent(Graphics g)
    {
        // Draws the image to the canvas
        g.drawImage(image, 0, 0, null);
    }



    public static void clear() {

        Graphics g = image.getGraphics();

        g.setColor(BACKGROUND_COL);

        g.fillRect(0, 0, image.getWidth(),  image.getHeight());



    }



public static void main(String[] args) {



    //Frame Start

    JFrame frame = new JFrame("My Title");
    LayoutManager layout = new BorderLayout();
    frame.setLayout(layout);
    frame.setSize(1000, 800);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(true);


    //Panel



    //GraphicalInterface panel = new GraphicalInterface();





    JPanel frame2 = new JPanel();
    Graphics g = frame2.getGraphics();

    frame2.setSize(500, 500);

    frame2.setVisible(true);

    frame2.setBackground(BACKGROUND_COL);











    //JText input START
    JTextField Field = new JTextField();

    //adds Field to frame and sets JTextField to bottom of app
    frame.add(Field, BorderLayout.PAGE_END);
    frame.add(frame2, BorderLayout.CENTER);

    //Sets welcome text within JText
    Field.setText("Enter command here:");

    //Calls aml from event lib, assigns to app
    Field.addMouseListener(new MouseAdapter() {

        //Clears text on click
          public void mouseClicked(MouseEvent e) {

            Field.setText("");
          }
        });


    //assign listener to field
    Field.addActionListener(new ActionListener() {

     //if statement for commands
        public void actionPerformed(ActionEvent e) {
            //assign variable to hold commands

            String command = Field.getText();





            if (command.equals("close")) {

                System.exit(0);

            }



            else if (command.equals("penup"))
            {

                g.drawLine(0, 20, 0, 0);

            }

            else if (command.equals("pendown"))
            {



            }

            else if (command.equals("turnleft"))
            {



            }

            else if (command.equals("turnright"))
            {



            }

            else if (command.equals("forward"))
            {



            }

            else if (command.equals("backward"))
            {



            }

            else if (command.equals("black"))
            {



            }

            else if (command.equals("green"))
            {



            }

            else if (command.equals("red"))
            {



            }
            else if (command.equals("reset"))
            {

                clear();

            }


        }
    });

    //JText input END





    //Menu


    //Creates Menu bar
    JMenuBar mbar = new JMenuBar();
    //Creates the actual drop down
    JMenu File = new JMenu("File");
    //Creates the second drop down
    JMenu Help = new JMenu("Help");

    //Creates button within Help drop down
    JButton About = new JButton("About");


    About.addActionListener( new ActionListener() {
        //Creates an event
         public void actionPerformed( ActionEvent e ) {


            //Calls the class Dialog.About
             Dialog.About(args);  


         }
        });

    //Creates a sub menu button from File
    JButton New = new JButton("New");


    New.addActionListener( new ActionListener() {
        //Creates an event
         public void actionPerformed( ActionEvent e ) {


            //Calls the class Dialog.New 
             Dialog.New(args);  

         }
        });

    //Creates a sub menu button from File
    JButton Load = new JButton("Load");


    Load.addActionListener( new ActionListener() {
        //Creates an event
         public void actionPerformed( ActionEvent e ) {


            //Calls the class Dialog.Load and runs code
             Dialog.Load(args);  


         }
        });


    //Creates a sub menu button from File
    JButton Save = new JButton("Save");

    //Listens for Save
    Save.addActionListener( new ActionListener() {
        //Creates an event
         public void actionPerformed( ActionEvent e ) {


            //Calls the class Dialog.Save and runs code
             Dialog.Save(args);  

         }
        });


    //asigns exit to a button
    JButton Exit = new JButton("Exit");

    //Listens for Save
    Exit.addActionListener( new ActionListener() {
        //Creates an event
         public void actionPerformed( ActionEvent e ) {


            //Calls the class Dialog.Save and runs code
             Diag.Exit(args);  

         }
        });





    //Assigns buttons to File and Help
    File.add(New);
    File.add(Load);
    File.add(Save);
    File.add(Exit);
    Help.add(About);
    mbar.add(File);
    mbar.add(Help);



    frame.setJMenuBar(mbar);

    File.setVisible(true);
    Help.setVisible(true);
    mbar.setVisible(true);
    frame.setVisible(true);

    //Menu end








}







    GraphicalInterface() {

        setPreferredSize(new Dimension(500, 300));

        image = new BufferedImage(800, 400, BufferedImage.TYPE_INT_RGB);

        // Set max size of the panel, so that is matches the max size of the image.
        setMaximumSize(new Dimension(image.getWidth(), image.getHeight()));

        clear();
    }













@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}








}
  • You forgot to post the error - you've only posted some lines further down the stack trace but not the one with the error. – Erwin Bolwidt Jul 04 '17 at 04:41
  • Apologies, the full console error will get updated – NotAFanOfJava Jul 04 '17 at 04:47
  • Alright, I've updated it. – NotAFanOfJava Jul 04 '17 at 04:51
  • Hey , the error is on this line `g.drawLine(0, 20, 0, 0);` , most likely g has not been assigned – Kenneth Clark Jul 04 '17 at 04:52
  • See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) – Andrew Thompson Jul 04 '17 at 04:52
  • I've been looking at this issue for roughly 4 hours and I've looked at assigning crap related to drawLine. Can anyone point out exactly why this is happening? I thought I had correctly assigned the graphics method – NotAFanOfJava Jul 04 '17 at 05:06
  • Your `frame2.getGraphics()` call is returning `null` as the JPanel hasn't been rendered yet. If you move this call to the `actionPerformed()` event handler you'll get a valid graphics object as the JPanel has been rendered by that point. You may not get the line you're trying to draw, but you will have fixed your immediate bug and have a valid graphics object. – cdlane Jul 04 '17 at 06:01

0 Answers0