我正在制作滑动拼图。 以下是我的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class GUI implements ActionListener{
private JFrame game; //Name the main window "game"
private JPanel borderPanel; //Declare borderPanel for main window
private BorderLayout border; //Name the borderPanel "border"
private ImageIcon[] image = new ImageIcon[12]; //Declare an array of images for tiles
private JButton[] tiles = new JButton[12]; //Declare an array for JButton inside the gridPanel
private JPanel gridPanel; //Declare gridPanel
private GridLayout grid; //Name the gridPanel "grid"
private int i; //Declare integer "i"
public GUI(){
game = new JFrame(); //Initial main window "game"
game.setTitle("Puzzle"); //Change window title to "Puzzle"
game.setSize(456, 392); //Set window size
game.setResizable(false); //fix the window's size
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
borderPanel = new JPanel(); //Declare borderPanel
border = new BorderLayout(); //Initial borderPanel
borderPanel.setLayout(border);
JButton newGameBtn = new JButton("New Game"); //Declare JButton "New Game"
borderPanel.add (newGameBtn, BorderLayout.PAGE_START); //Add a "new game" button on top
newGameBtn.addActionListener(this); //Add ActionListener function to JButton "newGamebtn"
gridPanel = new JPanel(); //Declare gridPanel for the tiles
GridLayout grid = new GridLayout(3, 4); //Give the gridPanel 12boxes
gridPanel.setLayout(grid); //Initial gridPanel
for (i = 0; i < 12; i++){
image[i] = new ImageIcon("bart" + i + ".jpg"); //link the array and images together
tiles[i] = new JButton(image[i]); //Setup 12 JButtons and place images onto JButtons
gridPanel.add(tiles[i]); //Add the tiles to gridPanel
}
borderPanel.add (gridPanel, BorderLayout.CENTER); //Put the gridPanel into the center of the borderPanel
game.add(borderPanel); //Add borderPanel to main frame
game.setVisible(true); //Make it visible
}
public void actionPerformed(ActionEvent click){
Collections.shuffle(Arrays.asList(tiles)); //Shuffle the the array "tiles" in an arraylist
shuffleTiles(); //Function to re-layout all tiles
}
public void shuffleTiles(){
gridPanel.removeAll(); //Remove all tiles in gridPanel
for (JButton tilesorder : tiles){ //For each element name "tilesorder" in "tiles
gridPanel.add(tilesorder); //Add all tiles back onto gridPanel with new order
}
gridPanel.repaint(); //Clean the area after remove tiles in case of old images are still there
gridPanel.revalidate(); //Re-layout the tiles
}
public static void main(String[] args){
GUI game = new GUI();
}
}
我已声明了2个数组,1个用于图像,1个用于图块。 我使用Collections.shuffle函数来洗牌。 截至目前,我可以洗牌,但我不知道如何交换瓷砖?
任何帮助将不胜感激。 感谢。