困扰了几天的问题了,大神来看哈啊。

qq_37171619 2017-07-10 03:06:37
public class MyFrame extends JFrame {
JLabel label;
JButton button[][] = new JButton[10][10];
ImageIcon im;

public MyFrame() {
label = new JLabel();
int count = 1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (count > 10) {
count = 1;
}
button[i][j] = new JButton(new ImageIcon("" + count++ + ".png"));

}
}
}

public void init() {
JButton temp;
for (int a = 0; a < 10000; a++) {
int m = (int) (Math.random() * 10);
int n = (int) (Math.random() * 10);
int o = (int) (Math.random() * 10);
int p = (int) (Math.random() * 10);
temp = button[m][n];
button[m][n] = button[o][p];
button[o][p] = temp;
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
button[i][j].addActionListener(new ButtonListener());
this.add(button[i][j]);
}
}
this.add(label);
this.setSize(500, 400);
this.setLayout(new GridLayout(11, 11));
this.setVisible(true);
}
}

public class ButtonListener implements ActionListener {

static int click = 1;
static JButton b1 = null;
static JButton b2 = null;

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub


if (click % 2 == 0) {
b2 = (JButton) e.getSource();
System.out.println("2");
} else {
b1 = (JButton) e.getSource();
b2 = null;
System.out.println("1");
}
click++;
if (b2 == null) {
System.out.println("b2为空!");
return;
} else {
if (b1.getIcon().toString() == b2.getIcon().toString()) {
b1.setVisible(false);
b2.setVisible(false);
System.out.println("消");
}
}
}
}

public class MainClass {
public static void main(String args[]){
MyFrame mf = new MyFrame();
mf.init();
}
}


我现在只是测试点两个相同图片让其消掉,但是没反应,点同一个图片两次却可以消掉。
...全文
262 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
HinanaiTenshi 2017-07-11
  • 打赏
  • 举报
回复
这取决于你怎么定义“相同的图片”,有个建议是这种业务核心点最好是个独立的方法,比如例子里应该抽一个比较图片是否相同的方法。 看代码的意思应该路径相同,那应该像楼上一样做路径的字符串比较,用Objects.equals(val1,val2)来实现即可。 如果是内容相同,那复杂度稍微高一些,需要比较图片的数据流一致。
wangyx92528 2017-07-11
  • 打赏
  • 举报
回复
b1.getIcon().toString() == b2.getIcon().toString() string 用equals 来判断应该就对了

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧