java龟兔赛跑图形界面
时间: 2023-07-15 14:15:07 浏览: 139
以下是一个简单的Java GUI程序,用于模拟龟兔赛跑。它使用了Java Swing库来创建图形用户界面,并使用Java多线程来模拟比赛过程。
```java
import javax.swing.*;
import java.awt.*;
public class TurtleAndRabbitRace extends JFrame {
private JLabel rabbitLabel, turtleLabel;
private JButton startButton;
private JPanel raceTrackPanel;
private int rabbitPosition, turtlePosition;
public TurtleAndRabbitRace() {
setTitle("Turtle and Rabbit Race");
setLayout(new BorderLayout());
// 创建兔子和乌龟的标签
rabbitLabel = new JLabel(new ImageIcon("rabbit.jpg"));
turtleLabel = new JLabel(new ImageIcon("turtle.jpg"));
// 将兔子和乌龟标签添加到赛道面板中
raceTrackPanel = new JPanel();
raceTrackPanel.setLayout(null);
raceTrackPanel.setPreferredSize(new Dimension(800, 200));
raceTrackPanel.add(rabbitLabel);
raceTrackPanel.add(turtleLabel);
rabbitLabel.setBounds(0, 0, 100, 100);
turtleLabel.setBounds(0, 100, 100, 100);
// 创建开始按钮
startButton = new JButton("Start");
startButton.addActionListener(e -> startRace());
// 将赛道面板和开始按钮添加到主面板中
add(raceTrackPanel, BorderLayout.CENTER);
add(startButton, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void startRace() {
// 创建兔子和乌龟的线程
Thread rabbitThread = new Thread(() -> {
while (rabbitPosition < 700) {
int distance = (int) (Math.random() * 10);
rabbitPosition += distance;
rabbitLabel.setLocation(rabbitPosition, 0);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
Thread turtleThread = new Thread(() -> {
while (turtlePosition < 700) {
int distance = (int) (Math.random() * 5);
turtlePosition += distance;
turtleLabel.setLocation(turtlePosition, 100);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
// 启动兔子和乌龟的线程
rabbitThread.start();
turtleThread.start();
}
public static void main(String[] args) {
new TurtleAndRabbitRace();
}
}
```
运行该程序,点击“Start”按钮即可开始比赛。程序模拟两个线程分别移动兔子和乌龟的位置,直到其中一个到达终点(即赛道的右侧)。
阅读全文