2015-06-19 184 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的。