Ich möchte das Symbol von 2 Jbuttons ändern, indem Sie eine und dann die nächste, um ihre Symbole zu tauschen. Etwas wie Candy Crush oder Bejeweled. Ich möchte Action-Listener verwenden, um dies zu erreichen, wie soll ich das machen? Tauschen Icons von 2 jbutton
ist dies die gui meines Programms:
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);
}
ich habe versucht, es zu tun, wie so
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);
}
Haben Sie Ihren versucht repaint() oder() nach dem Austausch erneut validieren? – Definity
Das Problem ist, dass ich nicht weiß, wie man auswechselt, weil ich nicht weiß, welche Taste gedrückt wird – john