执行操作后如何移动按钮?
How to move a button after action performed?
我正在开发一个使用 GridLayout 的程序。当我在执行操作后尝试将按钮移动到另一个位置时遇到问题。基本上,我在面板中有一个空的 space,大小只有一个按钮。我想将点击的按钮移动到这个空 space,相反,空 space 将取代这个按钮。我正在使用一个数组来获得一个看起来像框架的模型。所以我知道我的数组中的空 space 在哪里(这是 JButton 数组中的空值)并且我试图让这个按钮占据数组中空 space 的位置并且反之。但实际上并没有用。
我们将不胜感激。
private void setGame(int nbLines, int nbRows, int emptyX, int emptyY) {
pane.removeAll();
for (int i = 0; i < model.length; i++) {
for (int j = 0; j < model[i].length; j++) {
if (!(j == emptyY && emptyX == i)) {
button = new JButton("A");
model[i][j] = button;
pane.add(model[i][j]);
model[i][j].addActionListener(this);
}
}
}
frame.add(pane);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < model.length; i++) {
for (int j = 0; j < model[i].length; j++) {
if (e.getSource() == model[i][j]) {
System.out.println("Cordonnées de i : " + i + "Cordonnées de j : " + j);
model[i][j] = null;
setGame(nbLignes, nbCol, i, j);
}
}
}
}
Basically, i have an empty space in the panel with the size of a button.
你不能有空 space。您需要向面板添加一个实际组件以填充 GridLayout 中的 space。
所以我建议你可以这样做:
- 将所有按钮添加到 GridLayout
- 生成一个随机数以确定哪个单元格应为空。将此值保存为 "empty cell"。然后使用
Container.remove(...)
删除该单元格处的按钮。然后使用 Container.add(component, index)
方法添加一个没有文本的 JLabel 来填充空单元格。
- 然后,当您单击一个按钮时,您会使用
Container.getCompnent(...)
方法遍历面板中的所有组件,直到找到被单击按钮的索引。
- 现在您有两个索引,空单元格和单击的单元格。然后使用 remove(...) 和 add(...) 方法交换两个组件。
- 交换完成后,您将 "empty index" 更新为 "clicked index" 的值。
我正在开发一个使用 GridLayout 的程序。当我在执行操作后尝试将按钮移动到另一个位置时遇到问题。基本上,我在面板中有一个空的 space,大小只有一个按钮。我想将点击的按钮移动到这个空 space,相反,空 space 将取代这个按钮。我正在使用一个数组来获得一个看起来像框架的模型。所以我知道我的数组中的空 space 在哪里(这是 JButton 数组中的空值)并且我试图让这个按钮占据数组中空 space 的位置并且反之。但实际上并没有用。
我们将不胜感激。
private void setGame(int nbLines, int nbRows, int emptyX, int emptyY) {
pane.removeAll();
for (int i = 0; i < model.length; i++) {
for (int j = 0; j < model[i].length; j++) {
if (!(j == emptyY && emptyX == i)) {
button = new JButton("A");
model[i][j] = button;
pane.add(model[i][j]);
model[i][j].addActionListener(this);
}
}
}
frame.add(pane);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < model.length; i++) {
for (int j = 0; j < model[i].length; j++) {
if (e.getSource() == model[i][j]) {
System.out.println("Cordonnées de i : " + i + "Cordonnées de j : " + j);
model[i][j] = null;
setGame(nbLignes, nbCol, i, j);
}
}
}
}
Basically, i have an empty space in the panel with the size of a button.
你不能有空 space。您需要向面板添加一个实际组件以填充 GridLayout 中的 space。
所以我建议你可以这样做:
- 将所有按钮添加到 GridLayout
- 生成一个随机数以确定哪个单元格应为空。将此值保存为 "empty cell"。然后使用
Container.remove(...)
删除该单元格处的按钮。然后使用Container.add(component, index)
方法添加一个没有文本的 JLabel 来填充空单元格。 - 然后,当您单击一个按钮时,您会使用
Container.getCompnent(...)
方法遍历面板中的所有组件,直到找到被单击按钮的索引。 - 现在您有两个索引,空单元格和单击的单元格。然后使用 remove(...) 和 add(...) 方法交换两个组件。
- 交换完成后,您将 "empty index" 更新为 "clicked index" 的值。