简体   繁体   中英

Returning 2D array of Button from one class to another in java

I am facing a little problem in returning 2D array of Buttons from one class to another. It's giving (java.lang.NullPointerException) when I run this program :(

I made 3 classes..... 2 main classes are given below:

package chess;

import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Controller {

    private JFrame frame;
    private JPanel[][] panel;
    private JButton[][] c_buttons;
    private Players player;
    public int i,j;

    public Controller(){

        frame = new JFrame("Chess By HUS$AM");
        panel = new JPanel[10][10];
        c_buttons = new JButton[4][9];

        player = new Players();

        // HERE I AM RETURNING BUTTONS FROM Players CLASS USING METHOD...
        c_buttons = player.computer_pawn_players(); 

        for(i=1; i<=8; i++){
            for(j=1; j<=8; j++){

                panel[i][j]= new JPanel();

            }
        }

        for(j=1; j<=8; j++)
            panel[2][j].add(c_buttons[2][j]);

        frame.setLayout(new GridLayout(8,8));

        for(i=1; i<=8; i++){    
            for(j=1; j<=8; j++){
                frame.add(panel[i][j]);

                if ((i + j) % 2 == 0) panel[i][j].setBackground(Color.black);
                else panel[i][j].setBackground(Color.white);
            }   
        }//end outer for loop

        frame.setSize(600,500);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setVisible(true);


    }//end constructor

}//end controller class

Second Class is :

package chess;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class Players {

    private JButton[][] buttons;
    private Icon[][] icons;
    public int i,j;

    public void Players(){

        buttons = new JButton[4][9];
        icons = new ImageIcon[4][9];

        for(i=1; i<=8; i++)
            for(j=1; j<=8; j++)
                buttons[i][j] = new JButton();

        for(j=1; j<=8; j++)
            icons[1][j] = new ImageIcon(getClass().getResource("blackPawn"));

        for(j=1; j<=8; j++)
            buttons[2][j].setIcon(icons[1][j]);

    }

    public JButton[][] computer_pawn_players(){

        return buttons;

    }
}

If I get it your answer you want to return buttons from players to Controller? If so; In main class ceate a Players instance and;

JButton[][] getButton = players.computer_pawn_players();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM