java - 在java中将按钮的二维数组从一个类返回到另一个类

标签 java arrays user-interface jbutton

我在将 2D 按钮数组从一个类返回到另一个类时遇到了一个小问题。当我运行这个程序时,它给出了(java.lang.NullPointerException):(

我做了 3 个类(class)......下面给出了 2 个主要类(class):

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

第二类是:

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;

    }
}

最佳答案

如果我得到了你的答案,你想将按钮从玩家返回到 Controller 吗?如果是这样; 在主类中创建一个 Players 实例;

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

关于java - 在java中将按钮的二维数组从一个类返回到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25461953/

相关文章:

java - 运行 R scraper 脚本时出现 java.io.IOException 错误

arrays - 如果 var 似乎在 Swift 中深度复制数组。如果让?

c# - 如何使按钮看起来好像被按下了?

java - Windows 10 企业版 IntelliJ IDEA 中的 JDK 路径

java - 在 Java 中调用 Grep 会给出错误的结果,而在 shell 中调用 grep 会给出正确的结果

arrays - Scala 连接数组并减少值

java - 如何在 Java 中声明和初始化数组?

user-interface - Go GXUI - 如何设置文本框大小?

Java 功能测试

java - 如何从 Spring Security 中删除过滤器?