【发布时间】:2020-01-16 17:22:23
【问题描述】:
我目前正在尝试编写匹配游戏。我为JButton 和ImageIcon 创建了一个二维数组。我已经做了一个洗牌类名Shuffle 这个类洗牌ImageIcon 在它的数组中的位置。在没有基本卡的情况下开始游戏时,这些卡似乎是洗牌的。但是当我使用基本卡开始游戏并合并动作侦听器时,当您单击卡时没有图像。如果有人可以帮助我解决这个问题,将不胜感激。
考虑这段代码:
框架的方法:
void game() {
Shuffle shuffle = new Shuffle();
shuffle.random2();
ImageIcon base = new ImageIcon("images/BaseCard.png");
int x = 60;
int y = 20;
JFrame frame = obj.frame();
JLabel label = obj.label();
for (int i = 0; i < cards.length; ++i) {
for (int j = 0; j < cards[i].length; ++j) {
cards[i][j] = obj.Comp(base);
cards[i][j].addActionListener(new Clicked(i, j));
cards[i][j].setBounds(x, y, 90, 126);
y = y + 135;
if (y >= 540) {
y = 20;
x = x + 120;
}
frame.add(cards[i][j]);
}
}
frame.add(label);
frame.setLayout(null);
frame.setVisible(true);
}
}
这是 Shuffle 类:
class Shuffle {
Matching obj = new Matching();
String peach = "images/peach.png";
String daisy = "images/Baby_daisy.png";
String luigi = "images/Baby_Luigi.png";
String waluigi = "images/Baby_Waluigi.png";
String wario = "images/Baby_Wario.png";
String bowser = "images/BabyBowser.png";
String drybones = "images/DryBones.png";
String shyguy = "images/ShyGuy.png";
String[][] images = {
{peach, daisy, luigi, waluigi},
{wario, bowser, drybones, shyguy},
{peach, daisy, luigi, waluigi},
{wario, bowser, drybones, shyguy}
};
ImageIcon Icons[][] = new ImageIcon[4][4];
void random2() {
for (int i = 0; i < images.length; i++) {
for (int j = 0; j < images[i].length; j++) {
int i1 = (int) (Math.random() * images.length);
int j1 = (int) (Math.random() * images[i].length);
String temp = images[i][j];
images[i][j] = images[i1][j1];
images[i1][j1] = temp;
}
}
for (int i = 0; i < images.length; i++) {
for (int j = 0; j < images[i].length; j++) {
Icons[i][j] = new ImageIcon(images[i][j]);
}
}
}
}
这是动作监听器
class Clicked implements ActionListener {
Shuffle shuffle = new Shuffle();
Matching matching = new Matching();
private int i;
private int j;
public Clicked(int i, int j) {
this.i = i;
this.j = j;
}
public void actionPerformed(ActionEvent e) {
JToggleButton tBtn = (JToggleButton) e.getSource();
if (tBtn.isSelected()) {
System.out.println("click");
tBtn.setIcon(shuffle.Icons[i][j]);
} else {
System.out.println("not");
tBtn.setIcon(new ImageIcon("images/BaseCard.png"));
}
}
}
【问题讨论】:
-
为什么不添加几行代码并发布一个可以由其他人运行的minimal reproducible example?
标签: java arrays image swing shuffle