用Eclipse写一个Swing小游戏的代码
时间: 2024-01-25 20:04:32 浏览: 128
好的,以下是一个简单的Swing小游戏示例代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingGame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JButton button;
private int x, y;
public SwingGame() {
setTitle("Swing Game");
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, 20, 20);
}
};
button = new JButton("Start");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Thread thread = new Thread(new GameThread());
thread.start();
}
});
add(panel);
add(button, "South");
}
private class GameThread implements Runnable {
@Override
public void run() {
Random random = new Random();
while (true) {
x = random.nextInt(panel.getWidth() - 20);
y = random.nextInt(panel.getHeight() - 20);
panel.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
SwingGame game = new SwingGame();
game.setVisible(true);
}
}
这个小游戏随机在窗口中生成一个红色方块,每秒钟更新一次方块的位置。当用户点击Start按钮时,游戏开始。