我正在以一种非常简单的方式制作一个记忆图标游戏。我单击第二个按钮的图标时出现问题,但没有出现,但是代码可以解决其他所有问题,我认为问题出在actionPerformed方法中,我在其中处理被单击的按钮:
package ButtonsGsme;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Buttons extends JFrame implements ActionListener{
JButton lastPressed = null;
int buttonsPressed = 0;
Cards c = new Cards();
Icon[] iconPaths = {new ImageIcon(getClass().getResource("tiger.png")),
new ImageIcon(getClass().getResource("tiger.png")),
new ImageIcon(getClass().getResource("chicken.png")),
new ImageIcon(getClass().getResource("chicken.png"))};
ArrayList<Icon> icons = new ArrayList <>();
JButton buttonsArr[] = new JButton[4];
public Buttons(){
setLayout(null);
for(int i = 0; i < 4; i++) {
buttonsArr[i] = new JButton();
}
for(int i = 0; i < 4; i++) {
icons.add(iconPaths[i]);
}
Collections.shuffle(icons);
buttonsArr[0].setBounds(100, 100, 200, 140);
buttonsArr[1].setBounds(350, 100, 200, 140);
buttonsArr[2].setBounds(100, 300, 200, 140);
buttonsArr[3].setBounds(350, 300, 200, 140);
for (int i = 0; i < 4; i++) {
add(buttonsArr[i]);
buttonsArr[i].addActionListener(this);
}
}
// To give each button its icon
public void pressedIcon(JButton b) {
for (int i = 0; i < 4; i++){
if(b == buttonsArr[i]) {
buttonsArr[i].setIcon(icons.get(i));
}
}
}
public boolean matched(JButton b1, JButton b2){
if (b1.getIcon().toString().equals(b2.getIcon().toString())) {
return true;
}
else {
return false;
}
}
@Override
public void actionPerformed(ActionEvent e) {
buttonsPressed++;
pressedIcon((JButton) e.getSource());
if (buttonsPressed == 2) {
try {
// To stop a second with two buttons' icons show face up
TimeUnit.SECONDS.sleep(1);
}
catch (InterruptedException ex) {
Logger.getLogger(Buttons.class.getName()).log(Level.SEVERE, null, ex);
}
if (matched(lastPressed, (JButton) e.getSource()) == false) {
lastPressed.setIcon(null);
((JButton) e.getSource()).setIcon(null);
}
buttonsPressed = 0;
}
else {
lastPressed = (JButton) e.getSource();
}
}
}
这是当我单击第二个按钮(左下角)并保持一秒钟(我设置的计时器)后什么都没出现的情况