保存按钮供以后使用

时间:2014-06-01 12:39:06

标签: java swing nullpointerexception jbutton

我想保存此按钮,并在下次有人点击另一个按钮时更改它的图标,但它在我说的button2.setIcon(icon)行上给了我nullpointer异常; 。如何保存此按钮并在下次更改它的图标?或者如何在构造函数中访问按钮数组?有可能吗?

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 个答案:

答案 0 :(得分:0)

首先要说的是:您可以缩短代码。 而不是is_going_to_be_stable方法 你可以用这个:

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

而不是Set_Rows_Columns方法,您可以使用此

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

你不应该说

             private JButton button[];

你应该说

             private JButton[] button;

我不知道问题是否已解决。