[英]Returning 2D array of Button from one class to another in java
在将2D Buttons数组从一个类返回到另一个类时,我遇到了一个小问题。 当我运行该程序时,它给出了(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;
}
}
如果我得到您的回答,您想将按钮从播放器返回到控制器吗? 如果是这样的话; 在主类中创建一个Players实例;
JButton[][] getButton = players.computer_pawn_players();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.