Java Swing 实现字母连连看小游戏的代码
时间: 2023-11-13 13:04:19 浏览: 61
以下是一个简单的 Java Swing 实现字母连连看小游戏的代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class LetterLink extends JFrame implements ActionListener {
private JButton[][] board;
private JButton selected;
private int numRows, numCols;
private char[][] letters;
private Random random;
public LetterLink(int rows, int cols) {
super("Letter Link");
numRows = rows;
numCols = cols;
letters = new char[numRows][numCols];
board = new JButton[numRows][numCols];
random = new Random();
// 初始化字母矩阵
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
letters[i][j] = (char) ('A' + random.nextInt(26));
}
}
// 创建游戏面板
JPanel gamePanel = new JPanel(new GridLayout(numRows, numCols));
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
board[i][j] = new JButton("" + letters[i][j]);
board[i][j].addActionListener(this);
gamePanel.add(board[i][j]);
}
}
// 添加游戏面板到窗口
add(gamePanel);
// 设置窗口参数
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(numCols * 50, numRows * 50);
setLocationRelativeTo(null);
setVisible(true);
}
// 处理按钮点击事件
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
if (selected == null) {
selected = btn;
selected.setEnabled(false);
} else if (btn == selected) {
selected.setEnabled(true);
selected = null;
} else if (btn.getText().equals(selected.getText())) {
btn.setEnabled(false);
selected.setEnabled(false);
btn.setText("");
selected.setText("");
selected = null;
} else {
selected.setEnabled(true);
selected = btn;
selected.setEnabled(false);
}
}
public static void main(String[] args) {
new LetterLink(6, 6);
}
}
```
这个程序创建了一个大小为 6x6 的字母连连看游戏面板。每个按钮对应矩阵中的一个字母,当两个相同的字母被点击时,它们会消失。
你可以根据需要修改行数和列数,或者自定义字母矩阵的生成方式。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)