-1

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);


        }
    }
Jan
  • 3
  • 3
  • 2
    `"Puzzle.class.getResource("bloem.jpg")"` where is `bloem.jpg` file located? – Pshemo Jan 11 '15 at 13:36
  • In addition to that 1st comment, `Puzzle.class.getResource("bloem.jpg")` would better be `this.getClass().getResource("bloem.jpg")`.. – Andrew Thompson Jan 11 '15 at 13:59
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) One way to get images for an example, is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). 3) Use a logical and consistent form of indenting code lines and blocks. The indentation is intended to make the flow of the code easier to follow! 4) A single blank line of white space in source code is all that is *ever* needed. – Andrew Thompson Jan 11 '15 at 14:00
  • Oh, and `List Collections = new List(15);` should be `JList Collections = new JList(); Collections.setVisibleRowCount(15);`. Don't mix Swing and AWT components without good reason. Also, please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is a `CONSTANT`) and use it consistently. – Andrew Thompson Jan 11 '15 at 14:05

1 Answers1

0

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);
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • ow now i have change 1 row code to btArray[i]=new JButton(new ImageIcon(image)); now its works but only on 3buttons i got a part of my image the other buttons are empty. How can i solve this i gues its here image = createImage(new FilteredImageSource(source.getSource(), new CropImageFilter(i*width/3, i*height/4, (width/3)+1, height/4))); – Jan Jan 11 '15 at 14:42