我将一个按钮的2D数组从一个类返回到另一个类时遇到了一个小问题。它在我运行这个程序时给出(java.lang.NullPointerException):(
我做了3节课......下面给出了2个主要课程:
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;
}
}
答案 0 :(得分:2)
如果我得到你的回答你想要将玩家的按钮返回给控制器?如果是这样; 在主要类中停止一个玩家实例和;
JButton[][] getButton = players.computer_pawn_players();