是否可以在java awt中交换2个按钮引用?
如果交换了2个按钮,则应自动更新其名称。但是,即使在进行交换后调用button.repaint()也没有任何明显的变化。
使用button.setLabel("")更改按钮名称不是一个充分的解决方案。
按钮的事件被ActionListener捕获。请参阅从actionEvent转换为Button对象..
import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class Test extends Frame {
private static final long serialVersionUID = 1L;
private List<Button> buttons = new ArrayList<>();
private List<Button> buttonsToSwap = new ArrayList<>();
public Test() {
setLayout(new GridLayout(3, 3));
initButtons();
addButtons();
setSize(400, 400);
setVisible(true);
}
private void initButtons() {
for (int i = 0; i < 9; i++) {
buttons.add(new Button(Integer.toString(i + 1)));
}
}
private void addButtons() {
for (Button b : buttons) {
add(b);
b.addActionListener(new MyActionListener());
}
}
private class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
buttonsToSwap.add((Button) e.getSource());
if (buttonsToSwap.size() >= 2) {
buttonSwap(buttonsToSwap.get(0), buttonsToSwap.get(1));
buttonsToSwap.clear();
}
}
private void buttonSwap(Button b1, Button b2) {
Button temp = b1;
b1 = b2;
b2 = temp;
// button.repaint()???
}
}
public static void main(String[] args) {
new Test();
}
}