这是我写的一个就我到现在以来比较完善的小游戏了,接下来就介绍下我写连连看的具体思路
先创立好窗口,这也是实现游戏的第一步
public class lianliankan extends JFrame {
public void iniFrame() {
setTitle("连连看");
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setResizable(false);
setSize(700, 600);
setVisible(true);
}
public static void main(String[] args) {
lianliankan llk = new lianliankan();
llk.iniFrame();
}
}
二、添加两个面板在窗体上
public void addtablepanel() {
JPanel tablepanel = new JPanel();
tablepanel.setPreferredSize(new Dimension());
add(tablepanel);
}
public void addButtonpanel() {
JPanel buttonpanel = new JPanel();
buttonpanel.setPreferredSize(new Dimension(150, 0));
buttonpanel.setBackground(Color.blue);
add(buttonpanel, BorderLayout.EAST);
}
在iniFrame方法中也要添加,以方便主函数进行调用
setLayout(new BorderLayout());
addtablepanel();
addButtonpanel();
三、在包中创建另一个类,让代码简单化,在JTableModel后接口TableModel,然后将抽象具体化添加TableModel的具体方法
public class JTableModel implements TableModel {
String[][] data = new String[12][12];
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return data.length;
}
public String getColumnName(int columnIndex) {
return null;
}
public Class getColumnClass(int columnIndex) {
return String.class;
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return null;
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
public void addTableModelListener(TableModelListener l) {
}
public void removeTableModelListener(TableModelListener l) {
}
}
四、将方法中的返回值进行赋值
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return data.length;
}
public Class getColumnClass(int columnIndex) {
return ImageIcon.class;
}
public Object getValueAt(int rowIndex, int columnIndex) {
String path = data[rowIndex][columnIndex];
return new ImageIcon(path);
}
五、将图片引进表格,将图片打乱
public JTableModel() {
Random random = new Random();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
int index = random.nextInt(13) + 1;
data[i][j] = "image/" + index + ".jpg";
}
}
}
public JTableModel() {
Random random = new Random();
for (int i = 0; i < data.length / 2; i++) {
for (int j = 0; j < data[0].length; j++) {
int index = random.nextInt(13) + 1;
data[i][j] = "image/" + index + ".jpg";
data[i + data.length / 2][j] = "image/" + index + ".jpg";
}
}
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
int row = random.nextInt(data.length);
int column = random.nextInt(data[0].length);
String path = data[i][j];
data[i][j] = data[row][column];
data[row][column] = path;
}
}
}
六、设置好表格的宽度与高度
able.setRowHeight(50);
TableColumnModel tcm = able.getColumnModel();
int count = tcm.getColumnCount();
for (int i = 0; i < count; i++) {
tcm.getColumn(i).setPreferredWidth(54);
}