📄 boxgame.java
字号:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class BoxGame {
private JFrame jf;
private JButton[] array;
private static int row = 4;
private static int col = 4;
public static void main(String[] args) {
BoxGame thisClass = new BoxGame();
}
private BoxGame() {
jf = new JFrame("Sorting");
jf.setSize(400, 400);
jf.setLayout(new GridLayout(row, col));
array = new JButton[row * col];
for (int i = 0; i < row * col; i++) {
array[i] = new JButton();
array[i].addActionListener(new MyMonitor());
jf.add(array[i]);
}
setText();
jf.setVisible(true);
}
private void setText() {
ArrayList<String> numList = new ArrayList<String>();
for (int i=0; i<row*col; i++) {
if (i == row * col-1) {
numList.add("");
} else {
numList.add(String.valueOf(i+1));
}
}
for (int i =0; i<row*col; i++) {
int index =(int) (numList.size() * Math.random());
array[i].setText(numList.get(index));
numList.remove(index);
}
}
private class MyMonitor implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
if ("".equals(btn.getText())) {
return;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (btn == array[i * col + j]) {
String Num = btn.getText();
if (i > 0) {
JButton btnTop = array[(i - 1) * col + j];
if ("".equals(btnTop.getText())) {
btnTop.setText(Num);
btn.setText("");
check();
break;
}
}
if (i < row - 1) {
JButton btnBottom = array[(i + 1) * col + j];
if ("".equals(btnBottom.getText())) {
btnBottom.setText(Num);
btn.setText("");
check();
break;
}
}
if (j > 0) {
JButton btnLeft = array[i * col + j - 1];
if ("".equals(btnLeft.getText())) {
btnLeft.setText(Num);
btn.setText("");
check();
break;
}
}
if (j < col - 1) {
JButton btnRight = array[i * col + j + 1];
if ("".equals(btnRight.getText())) {
btnRight.setText(Num);
btn.setText("");
check();
break;
}
}
break;
}
}
}
}
private void check() {
// TODO Auto-generated method stub
boolean success = true;
for(int i=0;i<row*col;i++) {
JButton btn = array[i];
if(String.valueOf(i+1)!=btn.getText()){
success = false;
break;
}
}
if(success){
JFrame jf2 = new JFrame();
jf2.setLayout(new BorderLayout());
jf2.setSize(100, 100);
Button b2 = new Button("successful");
jf2.add(b2);
jf2.setVisible(true);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -