【问题标题】:2D array JButtons not working for get() methods? [closed]二维数组 JButtons 不适用于 get() 方法? [关闭]
【发布时间】:2013-03-19 00:15:54
【问题描述】:

我一直在尝试下国际象棋游戏,但被卡在交换两个棋子上

这是我的 ChessSquare 课

   public class ChessSquare extends JButton 



{ 




public int Yposition;
public int Xposition;
private String Type;
public ChessSquare( Icon s, int y , int x , String piece )

{
 super(s);

 Yposition = y;
 Xposition = x;
 Type = piece ;
}         

public int getXposition()
 {
   return this.Xposition;
 }  


    public int getYposition()
 {
   return this.Xposition;
 }  


    public String getType()
   {
      return "";
   }

 }  

然后我将其添加到 ChessBoard 类中,使用 ChessSquare 类作为 2D 数组

     public class ChessBoard extends JFrame implements ActionListener
  {
     String type;
     ChessSquare[][] s = new ChessSquare[8][8];
     int xPos1,xPos2,yPos1,yPos2,i,j;
     JPanel panel;


    ........


    public void actionPerformed(ActionEvent e)
  {
       Boolean flag = false ;

         if(!flag)
  {
     xPos1 = s.getYposition();
     yPos1 = s.getXposition();

     flag = true;
   }
     else
   {

    xPos2 = s.getYposition();
    yPos2 = s.getXposition();


    s[xPos1][yPos1] = s[xPos2][yPos2];
    s[xPos2][yPos2] = s[xPos1][yPos1];
    flag = false;


 }


 }

 } 

试图交换两件...但它不起作用?请帮忙...

【问题讨论】:

    标签: java swing get jbutton swap


    【解决方案1】:

    方法getXpositiongetYposition 是您的自定义ChessSquare 类的实例方法,而不是您的ChessSquare数组。要访问这些方法,您必须引用 2D 数组中的元素,例如:

    xPos1 = s[0][0].getYposition();
    yPos1 = s[0][0].getXposition();
    

    【讨论】:

    • 为什么要把简单的事情复杂化,不要那样做,而不是永远不要作为答案:-),它是关于准备你以前需要的所有东西,初始化 ....,see herehere (and see EventHandler == my love) ,并且使用的 LayoutManager 也可以返回坐标(在大多数情况下,JComponent 可以在此数组中交换,但(相同)在大多数情况下没有理由这样做 == 错误的概念)
    猜你喜欢
    • 2020-10-18
    • 2020-04-27
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多