CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2019
    Location
    Greece
    Posts
    1

    How to solve java.lang.NullPointerException

    I need to make a matching card game for an assignment in college. I've written the following code

    Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.IOException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Random;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.LineBorder;
    
    
    public class doFirst extends JFrame{
        public doFirst()  throws IOException{
            p = new JPanel();
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 1204, 908);
            p.setBackground(Color.WHITE);
            p.setBorder(new EmptyBorder(0,0,0,0));
            setContentPane(p);
            p.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
            
            p1 = new JPanel();
            p1.setBackground(Color.WHITE);
            p1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
            
            p2 = new JPanel();
            p2.setBorder(new LineBorder(new Color(0, 0, 0)));
            
            
            ln1 = new JLabel("Player:");
            ln1.setHorizontalAlignment(SwingConstants.CENTER);
            ln1.setVerticalAlignment(SwingConstants.TOP);
            
            l1 = new JLabel("0");
            l1.setHorizontalAlignment(SwingConstants.CENTER);
            l1.setVerticalAlignment(SwingConstants.TOP);
            l1.setForeground(Color.RED);
            
            
            ln2 = new JLabel("Computer: ");
            ln2.setHorizontalAlignment(SwingConstants.CENTER);
            ln2.setVerticalAlignment(SwingConstants.TOP);
            
            l2 = new JLabel("0");
            l2.setHorizontalAlignment(SwingConstants.CENTER);
            l2.setVerticalAlignment(SwingConstants.TOP);
            l2.setForeground(Color.RED);
            
            p2 = new JPanel();
            p2.setLayout(new GridLayout(2, 2, 20, 10));
            p2.add(ln1);
            p2.add(l1);
            p2.add(ln2);
            p2.add(l2);
            
             list1 = new ArrayList<Integer>();
            
            //insert the images to an array
            iconarray = new ImageIcon[14];
            iconarray[0] = new ImageIcon("1.png");
            iconarray[1] = new ImageIcon("2.png");
            iconarray[2] = new ImageIcon("3.png");
            iconarray[3] = new ImageIcon("4.png");
            iconarray[4] = new ImageIcon("5.png");
            iconarray[5] = new ImageIcon("6.png");
            iconarray[6] = new ImageIcon("7.png");
            iconarray[7] = new ImageIcon("8.png");
            iconarray[8] = new ImageIcon("9.png");
            iconarray[9] = new ImageIcon("10.png");
            iconarray[10] = new ImageIcon("11.png");
            iconarray[11] = new ImageIcon("12.png");
            iconarray[12] = new ImageIcon("flipped.png");
            iconarray[13] = new ImageIcon("empty.png");
            
            iconbuttonarray = new ImageIcon[10];
            for (int i = 0; i <10; i++) {
                iconbuttonarray[i] = iconarray[i];
                
            }
            list1.add(0);
            
            
             // add 12 JButtons to panel 1 and set initial icon
            for (int i = 0; i < 12; i++) {
                p1.add(new JButton(iconarray[12]));
                
                // insert JButtons in buttonarray
                buttonarray[i] = (JButton) p1.getComponent(i);
                
                // add ImageButtonListener method to each JButton
                buttonarray[i].addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e){
                    new ImageButtonListener();
                }
            });}  
            
                
            // add a number between 0 and 12 for each JButton
            int y = 0;
            while (y < 20) {
                int x = rand1.nextInt(10);
                list1.set(x, list1.get(x).intValue() + 1);
                if (list1.get(x) <= 2) {
                    buttonarray[y].setName(Integer.toString(x));
                    y++;
                }
            }
            
            timer1 = new Timer(2000, new TimerListener());
            
            
            
            p.add(p1);
            p.add(p2); 
        }
        
        private class TimerListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                b1.setIcon(iconarray[10]);
                b2.setIcon(iconarray[10]);
                timer1.stop();
                // active = true;
            }
        }
        
        // method to change JButton image
        private class ImageButtonListener implements ActionListener {
            @Override
            public void actionPerformed(ActionEvent e) {
                // waiting for timer to pop, user clicks not accepted
                if (timer1.isRunning())
                    return;
    
                for (int i = 0; i < 20; i++)
                    if (e.getSource() == buttonarray[i]) {
                        int x = Integer.parseInt(buttonarray[i].getName());
                        buttonarray[i].setIcon(iconarray[x]);
    
                        // button1=  first clicked button
                        if (counter == 1) {
                            b1 = buttonarray[i];
                            counter++;
                        }
                        // button 2= second clicked button, check I didn't click same card twice
                    if (counter == 2 && buttonarray[i] != b1) {
                            b2 = buttonarray[i];
                            compareicons();
                        }
                    }
            }
        
        
        // check if icons match
            private void compareicons() {
                if (b1.getIcon() == b2.getIcon()) {
                    
                    b1.setIcon(new ImageIcon(getClass().getResource("empty.png")));
                    b2.setIcon(new ImageIcon(getClass().getResource("empty.png")));
                    b1.setEnabled(false);
                    b2.setEnabled(false);
    
            //add up points to player who found two matching icons
                    if (player1 == true) {
                        points1++;
                        l1.setText(Integer.toString(points1));
                    } else {
                        points2++;
                        l2.setText(Integer.toString(points2));
                    }
                }
    
            //if cards are different, switch to other player
                else {
                    if (player1 == true) {
                        player1 = false;
                    } else {
                        player1 = true;
                    }
                    timer1.start();
                }
                //reset counter
                counter = 1;
            }
        }
        public static void main(String[] args){
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        doFirst frame = new doFirst();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        
        
        
        
        
        private JPanel p, p1, p2;
        private ImageIcon[] iconarray, iconbuttonarray;
        private ArrayList<Integer> list1;
        private JButton[] buttonarray;
        private Random rand1 = new Random();
        private JButton b1, b2;
        private int counter = 1;
        private Timer timer1;
        private int points1;
        private int points2;
        private boolean player1 = true;
        private final JLabel l1, l2, ln1, ln2;
    
    }
    and it gives me the following error

    java.lang.NullPointerException
    at memorygame.doFirst.<init>(doFirst.java:99)


    I made the line 99 red. I don't know exactly what the error is. I know NullPointerException occurs when I try to use an object that hasn't been initialized but how can I initialize it?

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: How to solve java.lang.NullPointerException

    Looks like an error in the line above the red line. Instead of:
    Code:
    p1.add(new JButton(iconarray[12]));
    Shouldn't it be:
    Code:
    p1.add(new JButton(iconarray[i]));

  3. #3
    Join Date
    Feb 2017
    Posts
    677

    Re: How to solve java.lang.NullPointerException

    Maybe it's because you declare buttonarray but never assign an array object to it?

    You could try,

    Code:
    private JButton[] buttonarray = new JButton[12];
    to check out whether that's the problem.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured