2015-06-19 154 views
0

因此,我将图像作为ImageIcon存储在JButton上。我希望用户点击他们想要使用的作品的JButton,然后点击另一个JButton将其移动到那里,我该怎么做?在Java中制作象棋游戏,我想移动棋子

我试过使用actionListener来获取ImageIcon,但其证明非常复杂,特别是因为我有一个JButton图像的2d数组。

ActionListener actionListener = new ActionListener() { 
      public void actionPerformed(ActionEvent actionEvent) { 

       System.out.println(actionEvent.getActionCommand()); 

      } 
     }; 

     JButton[][] squares = new JButton[8][8]; 
     Border emptyBorder = BorderFactory.createEmptyBorder(); 

     for (int row = 0; row < squares.length; row++) { 
      for (int col = 0; col < squares[row].length; col++) { 

       JButton tempButton = new JButton(); 

       tempButton.setBorder(emptyBorder); 
       tempButton.setSize(64, 64); 


       squares[row][col] = tempButton; 
       squares[row][col].addActionListener(actionListener); 
       panel.add(squares[row][col]); 

       squares[0][0].setIcon(new ImageIcon(BoardGUI.class.getResource("castle.png"), "castle")); 



      } 
     } 
+0

如果你包括了你所拥有的东西到底有什么问题,那么这对人们可能会有帮助。 – Galax

回答

0

请尝试以下代码。我不知道对Jbutton将ImageIcons工作确切的代码,但这种跨越得到的想法:

JButton pieceToMoveButton = null; //variable that persists between actionPerformed calls 

public void actionPerformed(ActionEvent actionEvent) 
{ 
    JButton button = (JButton)actionEvent.getSource(); 

    if (pieceToMoveButton == null) //if this button press is selecting the piece to move 
    { 
     //save the button used in piece selection for later use 
     pieceToMoveButton = button; 
    } 
    else  //if this button press is selecting where to move 
    { 
     //move the image to the new button (the one just pressed) 
     button.imageIcon = pieceToMoveButton.imageIcon 
     pieceToMoveButton = null; //makes the next button press a piece selection 
    } 
} 
0

不知道这是你在找什么,但单向移动JButton中的位置到另一个: 现在作为一个例子假装已经有代码声明和初始化JButton(JButton thatotherbutton = new JButton ...等)。它移动到某一位置可以做到这样:

Rectangle rect = thatotherbutton.getBounds(); 
xcoordinate = (int)rect.getX(); 
ycoordinate = (int)rect.getY(); 
chesspiecebutton.setBounds(xcoordinate, ycoordinate, xlengthofbutton, ylengthofbutton); 

在点击将另一个JButton使用这些坐标设定新的边界(换言之,位置)您的JButton的。