Hot questions for Using Applets in nullpointerexception

Top Java Programmings / Applets / nullpointerexception

Question:

Good evening all. I have been racking my brain trying to answer this question on my own but I am at a loss and considering throwing something. Let me preface my question with the fact that this was a school project that the instructor is letting me re-submit in an attempt to make a passing grade and I am not looking for a direct copy and past code but I need help to figure out how to solve this problem. The original code opens the applet and I get Start: applet not initialized error. In Eclipse, I get java.lang.NullPointerException with several lines that I have no idea where they came from. Please see code and errors list. Thanks in advance!

Error List
java.lang.NullPointerException
    at java.awt.Container.addImpl(Container.java:1091)
    at java.awt.Container.add(Container.java:971)
    at SodaMachine.init(SodaMachine.java:43)
    at sun.applet.AppletPanel.run(AppletPanel.java:434)
    at java.lang.Thread.run(Thread.java:745)
SodaMachine
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

@SuppressWarnings("serial")
public class SodaMachine extends Applet
{
    private TextField feedbackText;
    private TextField changeText;
    private TextField creditText;
    private Panel userMoneyPanel; //To hold Panel that shows current amount of money in machine, money due to user at end of transaction
    private Panel drinksPanel; //To hold Panel that shows available drink selections
    private Panel depositPanel; //To hold Panel that shows what money can be entered by user
    private Panel userFeedbackPanel;
    int colaStock = 3;
    int lemonLimeStock = 3;
    int grapeStock = 3;
    int rootBeerStock = 3;
    int waterStock = 3;
    double cost = 0.75;
    double credit = 0.00;
    double change = 0.00;


    public void init() 
    {

        //Panels to be built
        builduserMoneyPanel();
        builddrinksPanel();
        builddepositPanel();
        builduserFeedbackPanel();

        //layout manager for applet
        setLayout(new BorderLayout());

        //add Panels to applet
        add(depositPanel, BorderLayout.NORTH);
        add(userFeedbackPanel, BorderLayout.SOUTH);
        add(drinksPanel, BorderLayout.EAST);
        add(userMoneyPanel, BorderLayout.WEST);
    }

    //user Money Panel build method to show money in machine and user's change
    private void builduserMoneyPanel()
    {
        Panel userMoney = new Panel();
        Label creditLabel = new Label("Credit");
        Label changeLabel = new Label("Change");
        TextField creditText = new TextField(10);
        creditText.setEditable(false);
        TextField changeText = new TextField(10);
        changeText.setEditable(false);
        userMoney.setLayout(new GridLayout(2, 2));
        userMoney.add(creditLabel);
        userMoney.add(changeLabel);
        userMoney.add(creditText);
        userMoney.add(changeText);
    }

    //deposit method for user to add money to machine to make a transaction
    private void builddepositPanel()
    {
        Panel depositPanel = new Panel();
        Button nickelButton = new Button("INSERT NICKEL");
        Button dimeButton = new Button("INSERT DIME");
        Button quarterButton = new Button("INSERT QUARTER");
        Button dollarButton = new Button("INSERT DOLLAR");
        nickelButton.addActionListener(new nickelButtonListener());
        dimeButton.addActionListener(new dimeButtonListener());
        quarterButton.addActionListener(new quarterButtonListener());
        dollarButton.addActionListener(new dollarButtonListener());
        depositPanel.setLayout(new GridLayout(1, 4));
        depositPanel.add(nickelButton);
        depositPanel.add(dimeButton);
        depositPanel.add(quarterButton);
        depositPanel.add(dollarButton);
    }

    //method to show user available drink selection to choose from
    private void builddrinksPanel()
    {
        drinksPanel = new Panel();
        Button colaButton = new Button("COLA");
        Button lemonLimeButton = new Button("LEMON LIME");
        Button grapeButton = new Button("GRAPE");
        Button rootBeerButton = new Button("ROOT BEER");
        Button waterButton = new Button("WATER");
        colaButton.addActionListener(new colaButtonListener());
        lemonLimeButton.addActionListener(new lemonLimeButtonListener());
        grapeButton.addActionListener(new grapeButtonListener());
        rootBeerButton.addActionListener(new rootBeerButtonListener());
        waterButton.addActionListener(new waterButtonListener());
        drinksPanel.setLayout(new GridLayout(5, 1));
        drinksPanel.add(colaButton);
        drinksPanel.add(lemonLimeButton);
        drinksPanel.add(grapeButton);
        drinksPanel.add(rootBeerButton);
        drinksPanel.add(waterButton);
    }

    //method to tell user if drink is out of stock or if they have not added sufficent money to purchase drink
    private void builduserFeedbackPanel()
    {
        userFeedbackPanel = new Panel();
        TextField feedbackText = new TextField();
        feedbackText.setEditable(false);

    }

    //listeners for all drink choice buttons in applet
    private class colaButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");
            if(colaStock == 0)
            {
                feedbackText.setText("Insufficent stock available. Please make another selection.");
            }

            if(credit < cost)
            {
                feedbackText.setText("Insufficent funds. Please insert more money.");
            }

            if(credit >= cost)
            {
                colaStock -= 1;
                change = credit - cost;
                if(change == 0.00)
                {
                    changeText.setText("");
                }
                else
                {
                    changeText.setText(dollar.format(change));
                }
            }
        }
    }

    private class lemonLimeButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");

            if(lemonLimeStock == 0)
            {
                feedbackText.setText("Insufficent stock available. Please make another selection.");
            }

            if(credit < cost)
            {
                feedbackText.setText("Insufficent funds. Please insert more money.");
            }

            if(credit >= cost)
            {
                lemonLimeStock -= 1;
                change = credit - cost;
                if(change == 0.00)
                {
                    changeText.setText("");
                }
                else
                {
                    changeText.setText(dollar.format(change));
                }
            }
        }
    }

    private class grapeButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");

            if(grapeStock == 0)
            {
                feedbackText.setText("Insufficent stock available. Please make another selection.");
            }

            if(credit < cost)
            {
                feedbackText.setText("Insufficent funds. Please insert more money.");
            }

            if(credit >= cost)
            {
                grapeStock -= 1;
                change = credit - cost;
                if(change == 0.00)
                {
                    changeText.setText("");
                }
                else
                {
                    changeText.setText(dollar.format(change));
                }
            }
        }
    }

    private class rootBeerButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");

            if(rootBeerStock == 0)
            {
                feedbackText.setText("Insufficent stock available. Please make another selection.");
            }

            if(credit < cost)
            {
                feedbackText.setText("Insufficent funds. Please insert more money.");
            }

            if(credit >= cost)
            {
                rootBeerStock -= 1;
                change = credit - cost;
                if(change == 0.00)
                {
                    changeText.setText("");
                }
                else
                {
                    changeText.setText(dollar.format(change));
                }
            }
        }
    }

    private class waterButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");

            if(waterStock == 0)
            {
                feedbackText.setText("Insufficent stock available. Please make another selection.");
            }

            if(credit < cost)
            {
                feedbackText.setText("Insufficent funds. Please insert more money.");
            }

            if(credit >= cost)
            {
                waterStock -= 1;
                change = credit - cost;
                if(change == 0.00)
                {
                    changeText.setText("");
                }
                else
                {
                    changeText.setText(dollar.format(change));
                }
            }
        }
    }

    //listeners for all monetary choices available to user for purchasing drink
    private class nickelButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");
            credit += .05;
            creditText.setText(dollar.format(credit));
        }
    }

    private class dimeButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");
            credit += .10;
            creditText.setText(dollar.format(credit));
        }
    }

    private class quarterButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");
            credit += .25;
            creditText.setText(dollar.format(credit));
        }
    }

    private class dollarButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            DecimalFormat dollar = new DecimalFormat("'$'0.00");
            credit += 1.00;
            creditText.setText(dollar.format(credit));
        }
    }
}

Answer:

You are not setting fields in the builder methods. This means the fields are null when you add them to the container.

For example

  private Panel userMoneyPanel;
  ...

  private void builduserMoneyPanel()
  {
     // Panel userMoney = new Panel();  // this is wrong...
     userMoneyPanel = new Panel();
     ...

Question:

I am trying to display an icon on a button using the code posted below. But at run time, the console shows an NPE and highlights the code posted despite I am sure that the icon I wish to display on the button is placed in that path.

Note: the .. in the path is just a short for writing the whole path.

Code
ImageIcon iconplay = new ImageIcon (ClassLoader.getSystemResource("L:\\..\\..\\..\\..\\..\\..\\..\\..\\..\\Play.png"));

Answer:

  1. This is not a system resource, so don't try to use the system class loader. Something more like the following will use the context class loader.:

    URL url = this.getClass().getResource("/path/to/the.resource");
    
  2. That path starting with a drive letter is wrong. It should be a path relative to the class-path.

Question:

I am creating a program in java which reads a text file from applet and puts colors in applet window pixels defined by file. The problem is that when i run this program the Exception occurs and i have done everything i know to resolve it but didn't succeed.

My applet code is

GUIIO.java

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class GUIIO extends Applet {
Color color = new Color(2);
InputStream inputStream;
BufferedReader bufferedReader;

@Override
public void init() {
    try {
        inputStream = new FileInputStream("Sample In.txt");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void paint(Graphics g) {
    Point point = new Point();
    try {
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        point = this.getImageResolution(bufferedReader);
        char c, ch[] = {'a', 'b', 'c', 'd', 'e', 'f' };
        int i = 0, x = 0, y = 0;
        putPixel(1, 100, String.valueOf(ch), g);
        while((c = (char)bufferedReader.read()) != 'z') {
            if(c == 'y') {  
                y++;
                x = 0;
            }
            else if(i < 6) {
                ch[i] = c;
                i++;
            }
            if (i == 6) {
                putPixel(x, y, String.valueOf(ch), g);
                x++;
                i = 0;
                ch[i] = c;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    g.drawString(point.x+" "+point.y, 30, 10);
    repaint();
}

private Point getImageResolution(BufferedReader bufferedReader) throws IOException {
    boolean xFlag = false;
    StringBuilder x = new StringBuilder(), y = new StringBuilder();
    String check = null;
    char chars[] = bufferedReader.readLine().toCharArray();
    for(int i=0;i<chars.length;i++) {
        check = String.valueOf(chars[i]);
        if(check.equals("x"))   xFlag = true;
        else if(xFlag == true)  y.append(check);
        else    x.append(check);
    }
    Point point = new Point();
    point.x = Integer.parseInt(x.toString());
    point.y = Integer.parseInt(y.toString());
    return point;
}

private void putPixel(int x, int y, String color, Graphics g) {
    g.setColor(Color.decode("0x"+color));
    g.drawLine(x, y, x, y);
}
}

The input text file.

Sample In.txt

8x8
000000ff000000ff000000ff000000ff000000ff000000ffy000000ff000000ff000000ff000000ff000000ff000000ffy000000ff000000ff000000ff000000ff000000ff000000ffy000000ff000000ff000000ff000000ff000000ff000000ffy000000ff000000ff000000ff000000ff000000ff000000ffy000000ff000000ff000000ff000000ff000000ff000000ffy000000ff000000ff000000ff000000ff000000ff000000ffy000000ff000000ff000000ff000000ff000000ff000000ffyz

The exception or error i have got in eclipse

Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at GUIIO.getImageResolution(GUIIO.java:61)
at GUIIO.paint(GUIIO.java:30)
at sun.awt.RepaintArea.paintComponent(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(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.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.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)

Update: I have tried this code in cmd it runs perfectly but when i resized the window i gives same error.

Please help.


Answer:

There are muliple issues in your Code. First you can't read and read and read from your bufferedReader because at sometime it will be empty and you don't check if the line that you read from the bufferedReader is null.

There is also another problem, sometimes your color String is ?????? .

Why do you read the file every time the apllet is repainted? You could read the file once in your init() methode and that's it!

Question:

I get nullreferenceexception in my UI code.

idk what the problem is yesterday its works have changed some stuf and now it doesn't work anymore i think its something where i create the buttons

can someone look where i have maked the mistake

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.List;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;
import static javafx.scene.input.KeyCode.T;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Puzzle extends JFrame implements ActionListener
{
        /** JPanel variable */
        private JPanel centerPanel = new JPanel();
        private JPanel northPanel = new JPanel();
        private JPanel southPanel = new JPanel();

        /** JButton variable */
        private JButton newGame = new JButton("New Game"); 
        private JButton[] btArray = new JButton[15];
            List Collections = new List(15);



        /** JLabel variable */
        private JLabel moves = new JLabel("Moves : ");
        private JLabel label;

        private Container mainPanel = this.getContentPane();
        private int[][] pos;
        private int count;
        private String str;
            private Image source, image;

                   int width, height;



     public static <T> void shuffle(T[] array) {
    Random random = new Random();

    for (int i = array.length - 1 ; i >= 1; --i) {
        int j = random.nextInt(i);
        T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

        public Puzzle()
    {
            super("Puzzle Game");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            initUI();






        }


        public void initUI()
        {

       /*     pos = new int[][]{
                    {0, 1, 2},
                    {3, 4, 5},
                    {6, 7, 8}

          *///      };
                pos = new int[][]{
                    {0, 1, 2, 3},
                    {4, 5, 6, 7},
                        {8, 9, 10, 11},
                        {12, 13, 14, 15},

                };


         ImageIcon sid = new ImageIcon(Puzzle.class.getResource("bloem.jpg"));
        source = sid.getImage();

        width = sid.getIconWidth();
        height = sid.getIconHeight();



            /** Initialize button array */
            for (int i = 0; i < 15; i++)
            {
                image = createImage(new FilteredImageSource(source.getSource(),
                        new CropImageFilter(i*width/3, i*height/4, 
                            (width/3)+1, height/4)));

           // btArray[i] = new JButton("B" + i);
            btArray[i].setIcon(new ImageIcon(image));

         }








            /** North Panel */
            newGame.setFocusable(false);
            newGame.addActionListener(this);
            northPanel.setBackground(Color.red);
            northPanel.add(newGame);
            mainPanel.add(northPanel, BorderLayout.NORTH);

            /** South Panel */
            southPanel.add(moves);
            southPanel.setBackground(Color.LIGHT_GRAY);
            mainPanel.add(southPanel, BorderLayout.SOUTH);

            /** Game Panel */
        centerPanel.setLayout(new GridLayout(4, 4, 0, 0));
            centerPanel.setBackground(Color.BLACK);




            /** Add actionListeners to buttons */
            for (int i = 0; i < 15; i++)
        {
                btArray[i].addActionListener(this);
        }

            newGame();
        mainPanel.revalidate();
        label = new JLabel("");
            label.setBackground(Color.BLACK);
            centerPanel.add(label);
        mainPanel.add(centerPanel);
        }

        public void newGame()
        {

           count = 0;
               shuffle(btArray);

            for (int j = 14; j >= 0; j--)
            {
                centerPanel.remove(btArray[j]);

                       //   JOptionPane.showMessageDialog(null, "pfff");
            }


            for (int j = 14; j >= 0; j--)
            {
                centerPanel.add(btArray[j]);

            }
            centerPanel.revalidate();

        }



        public boolean isFinished()
            {
    {
            if ((btArray[0].getY() == btArray[1].getY() && btArray[1].getY() == btArray[2].getY()) && (btArray[3].getY() == btArray[4].getY() && btArray[4].getY() == btArray[5].getY())
                    && (btArray[6].getY() == btArray[7].getY()))
            {
                if (btArray[0].getX() == btArray[3].getX() && btArray[3].getX() == btArray[6].getX()
                        && btArray[1].getX() == btArray[4].getX() && btArray[4].getX() == btArray[7].getX()
                    && btArray[2].getX() == btArray[5].getX())
                {
                    return true;
                }
        }

            return false;
        }
            }


        public static void main(String[] args)
        {
        Puzzle puz = new Puzzle();
            puz.setBounds(20, 20, 300, 325);
            puz.setVisible(true);
        }




        public void actionPerformed(ActionEvent ae)
        {


            JButton button = (JButton) ae.getSource();
            Dimension size = button.getSize();

                if (isFinished())
            {
            JOptionPane.showMessageDialog(null, "You have Won the game");
            }

            if (ae.getSource() == newGame)
            {
                newGame();

            }



            int labelX = label.getX();
            int labelY = label.getY();
            int buttonX = button.getX();
       int buttonY = button.getY();
            int buttonPosX = buttonX / size.width;
            int buttonPosY = buttonY / size.height;
       int buttonIndex = pos[buttonPosY][buttonPosX];

       if (labelX == buttonX && (labelY - buttonY) == size.height) {

                int labelIndex = buttonIndex + 4;

                centerPanel.remove(buttonIndex);
                centerPanel.add(label, buttonIndex);
                centerPanel.add(button, labelIndex);
                centerPanel.validate();
                count++;

            }

            if (labelX == buttonX && (labelY - buttonY) == -size.height) {

                int labelIndex = buttonIndex - 4;
                centerPanel.remove(labelIndex);
                centerPanel.add(button, labelIndex);
                centerPanel.add(label, buttonIndex);
                centerPanel.validate();
                count++;

            }

        if (labelY == buttonY && (labelX - buttonX) == size.width) {

                int labelIndex = buttonIndex + 1;

                centerPanel.remove(buttonIndex);
            centerPanel.add(label, buttonIndex);
                centerPanel.add(button, labelIndex);
           centerPanel.validate();
           count++;

            }

            if (labelY == buttonY && (labelX - buttonX) == -size.width) {

                int labelIndex = buttonIndex - 1;

                centerPanel.remove(buttonIndex);
                centerPanel.add(label, labelIndex);
                centerPanel.add(button, labelIndex);
                centerPanel.validate();
                count++;

            }

        str = String.valueOf(count);
            moves.setText("Moves : " + str);


        }
    }

Answer:

Your Null Pointer Exception may be caused for two reasons:

  1. your image isn't placed in same location as your class

or more probable

  1. you didn't fill your btArray array with instances of JButton so it is filled with default values (nulls) but you are trying to invoke btArray[i].setIcon(imageIcon); which means that this code will be same as null.setIcon(imageIcon) (but null doesn't have any methods or fields).

To solve first problem make sure that your file is located in same directory as your Puzzle.class.

To solve second problem add

for (int i=0; i<btArray.length;i++){
    btArray[i]=new JButton();
}

in your initUI method to actually fill btArray with JButton instances.

In Java 8 you can do it all while declaration (more info at Java 8 fill array with supplier)

private JButton[] btArray = Stream.generate(JButton::new).limit(15)
        .toArray(JButton[]::new);