62,628
社区成员
发帖
与我相关
我的任务
分享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();
}
}