Java, Как поменять положение компонентов по горизонтали и вертикали в GridLayout? - PullRequest
1 голос
/ 25 октября 2019

Я получил задание на создание 15 головоломок. Где игрок может поменять плитку номера, только если пустая плитка находится рядом с ней по горизонтали или вертикали. Я полагал, что мое решение этого было создать Gridlayout 4x4. И 2d массив для поиска местоположения определенной кнопки, чтобы я мог поменять местами кнопки друг с другом, если это имеет какой-то смысл ...

Проблема в том, что я использую panel.add(button0, row, col). Он не имеет x и y местоположений, как у 2d массива, что я и думал. Это привело к тому, что кнопка оказалась в неправильных местах.

Как я могу использовать то, что у меня есть, для решения моей проблемы, или мне нужно начинать все сначала?

Заранее спасибо!

class GameTest extends JFrame implements ActionListener{

JPanel panel = new JPanel();
JButton[][] buttons = new JButton[4][4];
JButton button0 = new JButton("EMPTY");

public GameTest() {
    add(panel);
    setBackground(Color.RED);
    panel.setLayout(new GridLayout(4,4));
    int i = 1;
    for (int row = 0; row < buttons.length; row++) {
        for (int col = 0; col < buttons.length; col++ ) {
            if (row == 3 && col == 3) {
                buttons[row][col] = button0;
                panel.add(buttons[row][col]);
                buttons[row][col].setBackground(Color.WHITE);
                buttons[row][col].setName("button0");
            }
            else{
                buttons[row][col] = new JButton(i + "");
                panel.add(buttons[row][col]);
                buttons[row][col].addActionListener(this);
                buttons[row][col].setBackground(Color.RED);
                buttons[row][col].setName("button" + i);
                buttons[row][col].setFont(new Font("Arial", Font.PLAIN, 30));
                i++;
            }
        }
    }
    setCursor(new Cursor(Cursor.HAND_CURSOR));
    setResizable(false);
    setLocation(500,200);
    setSize(400,400);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}


public boolean isSwappable(JButton button) {
    for (int row = 0; row < buttons.length; row++) {
        for (int col = 0; col < buttons.length; col++ ) {
            if (buttons[row][col] == button) {
                if (row != 3 ) {
                    if (buttons[row+1][col] == button0){
                        return true;
                    }
                }
                else if (col != 3){
                    if (buttons[row][col+1] == button0){
                        return true;
                    }
                }
                else if (row != 0) {
                    if (buttons[row-1][col] == button0) {
                        return true;
                    }
                }
                else if (col != 0) {
                    if ( buttons[row][col-1] == button0){
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

@Override
public void actionPerformed(ActionEvent e) {
    JButton source = (JButton)e.getSource();
    if (isSwappable(source)) {
        int x = 0;
        int y = 0;
        JButton buttonTemp = null;
        JButton buttonTemp0 = null;
        for (int row = 0; row < buttons.length; row++) {
            for (int col = 0; col < buttons.length; col++) {
                if (buttons[row][col] == source) {
                    buttonTemp = source;

                    buttonTemp0 = button0;
                    x = row;
                    y = col;

                }
                if (buttons[row][col] == button0) {
                    buttons[row][col] = buttonTemp;
                    buttons[x][y] = buttonTemp0;
                }
            }
        }
    }
  }
}

1 Ответ

2 голосов
/ 25 октября 2019

У него нет x и y местоположений, как у 2d массива,

Правильно, это одномерный массив.

Так что вам нужно вычислитьиндекс, используя 2D информацию.

Так, например, если вы хотите поменять местами расположение строки = 1 и столбца = 2

Индекс будет:

int index = (row * 4) + column;
...