如何在JPanel上随机按钮进行游戏滑动拼图?

时间:2016-03-14 15:12:53

标签: java algorithm swing jpanel jbutton

今天我在IDE Netbean中使用java创建了游戏Sliding Puzzle。我还用3 * 3行和col图片创建了它,用于按钮上的设置图像。我只能在jpanel中创建索引的按钮序列。我怎么能随机定位按钮与图像,但要确保它记住匹配的图片面板中的位置。我怎么知道它赢了?如果我的信息不够,请多多问我。

     position = new int[row][col];
            lstBtn = new JButton[row][col];
            count = new int[row * col];
            panelContainer.setLayout(null);
            panelContainer.setLayout(new GridLayout(row, col));
            BufferedImage img;
            int numCount = 0;
            int posNum=0;
            for (int i = 0; i < row; i++) {


 for (int j = 0; j < col; j++) {

                position[i][j] = posNum++;

                if (i == 0 & j == 0) {
                    lstBtn[i][j] = new JButton();
                    lstBtn[i][j].setBackground(Color.WHITE);
                    lstBtn[i][j].setBorderPainted(false);
                    panelContainer.add(lstBtn[i][j], numCount);
                    count[0] = numCount;
                } else {
                      numCount++;

                    lstBtn[i][j] = new JButton();
                    lstBtn[i][j].addActionListener(this);

                //   img = image_cutting.getSubImage(j,i);//160, 116 //120, 87,
                //  lstBtn[i][j].setIcon(new ImageIcon(img.getScaledInstance(160, 116, BufferedImage.SCALE_SMOOTH)));
                    lstBtn[i][j].setHorizontalTextPosition(JButton.CENTER);
                    lstBtn[i][j].setVerticalTextPosition(JButton.CENTER);
                    lstBtn[i][j].setFont(new Font("Dialog",2,20));
                    lstBtn[i][j].setForeground(Color.BLUE);

                    lstBtn[i][j].setText("" + numCount);

                    panelContainer.add(lstBtn[i][j], numCount);
                    lstBtn[i][j].setVisible(true);
                    System.out.println(numCount);
                }
                if (numCount == 0) {
                    continue;
                }
                count[numCount] = numCount;
            }
        }

0 个答案:

没有答案