我想通过选择一个来改变2个Jbuttons的图标,然后选择下一个来交换它们的图标。喜欢糖果粉碎或宝石迷阵的东西。 我想用动作监听器来完成这个,我该怎么做呢?
这是我的计划的gui:
public class UI implements Runnable {
private JFrame _frame;
private Model _model;
private ArrayList<JButton> _tiles;
public void run() {
_model = new Model();
_frame = new JFrame();
_frame.setLayout(new GridLayout(5,5));
_tiles = new ArrayList<JButton>();
for (int i=0; i<25; i++) {
JButton tile = new JButton();
tile.setBackground(Color.white);
//this just pick out random icon file from a folder
tile.setIcon(_model.randomIcon());
tile.addActionListener(new ButtonBorderHandler(_model,tile));
//this is the actionlistener that i want to implement the swap on
tile.addActionListener(new ButtonSwapHandler();
_tiles.add(tile);
}
我试过这样做
public class ButtonSwapHandler implements ActionListener{
JButton _button1;
JButton _button2;
Model _model;
UI _ui;
public ButtonSwapHandler(UI u,Model m, JButton b1, JButton b2){
_model=m;
_button1=b1;
_button2=b2;
_ui =u;
}
@Override
public void actionPerformed(ActionEvent e) {
//this line should give me the position of the first button i press
int i = _ui.getTiles().indexOf(e.getSource());
//this is the part where i dont know how to keep going
//i want to know where is the 2nd button that i clicked
int j = _ui.getTiles().indexOf(e.
// this is the method i wrote to make the swap
// it just the Collections.swap(tile,positionOfButton1,postionOfButton2)
_model.swap(ui._tile,i,j);
}
答案 0 :(得分:0)
你的逻辑不太清晰。您正在创建一个5x5网格,您可以在其中填充按钮。
例如:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
但是,当您点击按钮时,如何确保交换方向?比如说,如果用户点击按钮7,应该选择7的相邻按钮进行交换?
所以,你的逻辑中缺少的是方向。
例如:
如果交换始终发生在左侧立即按钮,您可以像indexOf(selectedButton)-1
一样计算交换按钮。同样,只有当该二维网格中的那行具有立即左键时,交换才可能在条件基础上发生。
<强>更新强>
如果操作只在单击两个按钮后发生,那么您需要再创建一个类,它实际上跟踪点击的按钮数量,然后在count == 2时交换。
以下是一个修改过的示例:
public class ButtonClicksCounter {
static ArrayList<JButton> _buttonsClicked = new ArrayList<JButton>();
public static void addButton(JButton btn) {
_buttonsClicked.add(btn);
}
public static int getButtonClicksCount() {
return _buttonsClicked.size();
}
public static void clearButtonClicksCount() {
_buttonsClicked.clear();
}
public ArrayList<JButton> getButtonsClicked() {
return _buttonsClicked;
}
}
public class ButtonSwapHandler implements ActionListener{
JButton _button;
Model _model;
UI _ui;
public ButtonSwapHandler(UI u, Model m, JButton b1){
_model=m;
_button=b1;
_ui =u;
}
@Override
public void actionPerformed(ActionEvent e) {
//Add the button
ButtonClicksCounter.addButton((JButton)e.getSource());
//Check if count==2
if(ButtonClicksCounter.getButtonClicksCount()==2) {
ArrayList<JButton> buttonsToSwap = ButtonClicksCounter.getButtonsClicked();
//Get positions
int i = _ui.getTiles().indexOf(buttonsToSwap[0]);
int j = _ui.getTiles().indexOf(buttonsToSwap[1]);
//Swap
_model.swap(ui._tile,i,j);
//Clear selection
ButtonClicksCounter.clearButtonClicksCount();
}
}