-3

I want to save this button and change it's icon the next time someone clicks on another button, but it gives me nullpointer exception on the line that i say button2.setIcon(icon); . How can I save this button and change it's icon the next time? Or how can i access the button array in the constructor? Is it possible?

package tictactoe;

// import necessary classes and interfaces
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class TicTacToeGame  extends JFrame {

    /**
     * 
     */
    boolean lock=false;
    //int for_the_first_time=1;
    int temp1;
    int temp2;
    int selected=0;
    Icon ic;
    int row ;
    int col ;
    Icon[] array = new Icon[12];
    Icon[] arrayc = new Icon[12];
    int[] random_array = new int[12];
    int[] arrayint = new int[12];
    int[] arrayintc = new int[12];
    private static final long serialVersionUID = 1L;
    private final static int ROWS = 3;
    private final static int COLUMNS = 4;
    private JButton button[];
    private JPanel buttonsPanel;
    private JButton exitButton;
    Icon icon = new ImageIcon(getClass().getResource("scene.jpg"));


    public TicTacToeGame()
    {
        // set frame's title
        this.setTitle( "Remember Me" );

        buttonsPanel = new JPanel();

        // set panel's layout manager
        buttonsPanel.setLayout( new GridLayout( ROWS , COLUMNS , 1 , 1 ) );

        // create a JButton object named exitButton
        exitButton = new JButton("Exit");

        //register an ActionListener for exitButton
        exitButton.addActionListener(
           new ActionListener()
           {
               public void actionPerformed( ActionEvent ae )
               {
                   // do a normal exit
                   System.exit( 0 );
               }
           }
        );

        // add exitButton to frame
        this.add( exitButton , BorderLayout.SOUTH );

        // create an array of JButtons
        button = new JButton[ ROWS * COLUMNS ];

        // initialize each button and add it to buttonsPanel

        for ( int i = 0 ; i < 12 ; i++ ) {
            array[i]= new ImageIcon(getClass().getResource(i+".jpg"));
            arrayint[i]=i;

        }
//create not repeating random numbers:
        Random rng = new Random(); // Ideally just create one instance globally
     // Note: use LinkedHashSet to maintain insertion order
     Set<Integer> generated = new LinkedHashSet<Integer>();
     while (generated.size() < 12)
     {
         Integer next = rng.nextInt(12);
         // As we're adding to a set, this will automatically do a containment check
         generated.add(next);
     }

     String str = generated.toString();
     str = str.replaceAll("\\s", "");
     str = str.replace("[", "");
     str = str.replace("]", "");
     String[] str2= str.split(",");
     for (int i=0;i<12;i++){
        random_array[i]= Integer.parseInt(str2[i]);
     }
        for (int i=0;i<12;i++){

        arrayc[i]=array[random_array[i]];
        arrayintc[i]=arrayint[random_array[i]];
        }

        for ( int i = 0 ; i < ROWS * COLUMNS ; i++ ) {
               button[ i ] = new JButton();
               button[ i ].setFocusPainted( false );
               button[ i ].setActionCommand( Integer.toString( i ) );
               button[ i ].setFont( new Font( "Tahoma" , Font.BOLD , 15 ) );
               button[ i ].setPreferredSize( new Dimension( 100 , 100 ) );
               button[ i ].setToolTipText( "Click to make your move" );
               button[ i ].addActionListener( new ButtonClickHandler() );
               button[ i ].setIcon(arrayc[i]);
               buttonsPanel.add( button[ i ] );

        }


        // add buttonsPanel to frame
        this.add(buttonsPanel, BorderLayout.NORTH);

        // set some of JFrame's propeties
        this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        // don't allow user to resize the Jframe
        this.setResizable( false );

        // resize frame to a suitable size
        this.pack();

        // don't allow user to resize the game window
        this.setVisible( true );

        try{
            Thread.sleep(2000);
            for ( int i = 0 ; i < ROWS * COLUMNS ; i++ ) {
                button[ i ].setIcon(icon);
        }

     }catch(InterruptedException e){

     }
       // resetGame();


    } // end of class constructor


    private class ButtonClickHandler implements ActionListener
    {


        public void actionPerformed( ActionEvent event )
        {
            int count=0;
             JButton button = (JButton) event.getSource();
             Set_Rows_Columns(button);  
             check_if_possible_to_show(count, button);
        }

        JButton  button2;
        int for_the_first_time=1;
        boolean stable=false;
        private void check_if_possible_to_show(int count, JButton button) {

            if (selected==1){
                button2.setIcon(icon);
                is_going_to_be_stable(temp1,arrayintc[count],count,button);
                }
            else{
                temp1=arrayintc[count];
                button2=button;



                selected=1;
                button.setIcon(arrayc[count]);
            }       }

        private void is_going_to_be_stable(int temp1, int temp2,int count, JButton button) {
            int temp1v;
            int temp2v;
            boolean bool=false;
            if (temp1==0){
                if (temp2==6){
                    bool= true;
                }
            }

            if (temp1==1){
                if (temp2==7){
                    bool= true;
                }
            }
            if (temp1==2){
                if (temp2==8){
                    bool= true;
                }
            }
            if (temp1==3){
                if (temp2==9){
                    bool= true;
                }
            }
            if (temp1==4){
                if (temp2==10){
                    bool= true;
                }
            }
            if (temp1==5){
                if (temp2==11){
                    bool= true;
                }
            }
            if (bool==true){

                 button.setIcon(arrayc[count]);
                 button2.setIcon(arrayc[1]);

            }
            else{
                button2.setIcon(icon);
                button.setIcon(arrayc[count]);
            }

        }

        public void Set_Rows_Columns(JButton button) {
            if(button.getActionCommand().equals("0")){
                 row=0; col=0;
             }
             if(button.getActionCommand().equals("1")){
                 row=0; col=1;
             }
             if (button.getActionCommand().equals("2")){
                 row=0; col=2;
             }
             if (button.getActionCommand().equals("3")){
                 row=0; col=3;
             }
             if (button.getActionCommand().equals("4")){
                 row=1; col=0;
             }
             if (button.getActionCommand().equals("5")){
                 row=1; col=1;
             }
             if (button.getActionCommand().equals("6")){
                 row=1; col=2;
             }
             if (button.getActionCommand().equals("7")){
                 row=1; col=3;
             }
             if (button.getActionCommand().equals("8")){
                 row=2; col=0;
             }
             if (button.getActionCommand().equals("9")){
                 row=2; col=1;
             }
             if (button.getActionCommand().equals("10")){
                 row=2; col=2;
             }
             if (button.getActionCommand().equals("11")){
                 row=2; col=3;
             }
        }

    }
} // end of class TicTacToeGame
  • 1
    `it gives me nullpointer exception` Can you specify the exception stacktrace and which line is causing it? It will be great help. – Unihedron Jun 01 '14 at 12:45
  • 1
    Get rid of `Thread.sleep(2000);` as this has no business being called on the Swing event thread. I agree with @Unihedron, that your question is very incomplete. You need to show us which line throws the NPE, and you need to tell us more about your program. Please don't force us to guess or to go through lots of unrelated code. – Hovercraft Full Of Eels Jun 01 '14 at 13:31
  • well , this is a game that the user needs to see the pictures and remember their places so i need to use thread.sleep(2000); – user3688188 Jun 01 '14 at 14:10
  • on the line that i say `button2.setIcon(icon);` i get nullpointer ecxeption although i have saved the previous button in the line that i say : `button2=button;` ill do it on perpous by clicking on a button and then click on another button so the else statement would run – user3688188 Jun 01 '14 at 14:12

1 Answers1

0

First thing to say: you can short your code. Instead of the is_going_to_be_stable method you can use this:

        if (
             (temp1 == 0 && temp2 == 6) ||
             (temp1 == 1 && temp2 == 7) ||
             (temp1 == 2 && temp2 == 8) ||
             (temp1 == 3 && temp2 == 9) ||
             (temp1 == 4 && temp2 == 10) ||
             (temp1 == 5 && temp2 == 11)
          ){

             button.setIcon(arrayc[count]);
             button2.setIcon(arrayc[1]);

        } else{ 
            button2.setIcon(icon);
            button.setIcon(arrayc[count]);
        }

And instead of the Set_Rows_Columns method you can use this

        switch(button.getActionCommand()){
               case "0":
                    row=0; col=0;
               break;
        //and so on
        }

And you shouldn't say

             private JButton button[];

you should say

             private JButton[] button;

I don't know if the problem is fixed or not.

SchokoTets
  • 1
  • 1
  • 4