如何使用Java写一个小游戏
时间: 2023-07-20 18:16:31 浏览: 45
使用Java编写小游戏可以采用Java Swing库或者JavaFX库,以下是一个简单的Java Swing小游戏的示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JButton button;
JLabel label;
MyGame() {
setTitle("My Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new FlowLayout());
button = new JButton("Click Me");
label = new JLabel();
add(button);
add(label);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
public static void main(String[] args) {
new MyGame();
}
}
```
这个小游戏只有一个按钮,当用户点击按钮时,文本标签会显示“Button Clicked!”。你可以根据自己的需要修改代码,添加更多的组件和功能。