import javax.swing.*;import java.awt.*;import java.util.Random;public class TicketSeller { private JFrame mainFrame; private JPanel panel; private JProgressBar progressBar1; private JProgressBar progressBar2; private JLabel label1; private JLabel label2; private JButton startButton; private int totalTickets = 108; private int ticketSold1 = 0; private int ticketSold2 = 0; public TicketSeller() { prepareGUI(); addComponents(); } private void prepareGUI() { mainFrame = new JFrame("Ticket Seller"); mainFrame.setSize(400, 200); mainFrame.setLayout(new GridLayout(2, 1)); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void addComponents() { panel = new JPanel(new GridLayout(2, 2)); label1 = new JLabel("LYH_1_108_1"); progressBar1 = new JProgressBar(0, totalTickets); progressBar1.setValue(0); panel.add(label1); panel.add(progressBar1); label2 = new JLabel("LYH_1_108_2"); progressBar2 = new JProgressBar(0, totalTickets); progressBar2.setValue(0); panel.add(label2); panel.add(progressBar2); mainFrame.add(panel); startButton = new JButton("Start"); startButton.addActionListener(e -> { Thread thread1 = new Thread(() -> sellTickets(1)); Thread thread2 = new Thread(() -> sellTickets(2)); thread1.start(); thread2.start(); }); mainFrame.add(startButton); mainFrame.setVisible(true); } private void sellTickets(int windowNum) { while (ticketSold1 + ticketSold2 < totalTickets) { int ticketSold = new Random().nextInt(5) + 1; if (windowNum == 1) { if (ticketSold1 + ticketSold <= totalTickets) { ticketSold1 += ticketSold; progressBar1.setValue(ticketSold1); } } else { if (ticketSold2 + ticketSold <= totalTickets) { ticketSold2 += ticketSold; progressBar2.setValue(ticketSold2); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { new TicketSeller(); }}
时间: 2024-01-15 22:03:15 浏览: 187
java写的小游戏贪吃蛇代码1[指南].doc
这段代码是一个简单的模拟售票程序,它创建了一个窗口,包含两个进度条和一个“开始”按钮。总共有 108 张票,两个窗口分别出售随机数量的票,直到所有票都售出为止。
要显示已售票的份数,可以在程序中添加一个标签或文本框,每次销售后更新它的文本。例如,在 `sellTickets()` 方法中,可以添加以下代码:
```java
if (windowNum == 1) {
if (ticketSold1 + ticketSold <= totalTickets) {
ticketSold1 += ticketSold;
progressBar1.setValue(ticketSold1);
label1.setText("LYH_1_108_1: " + ticketSold1 + " sold");
}
} else {
if (ticketSold2 + ticketSold <= totalTickets) {
ticketSold2 += ticketSold;
progressBar2.setValue(ticketSold2);
label2.setText("LYH_1_108_2: " + ticketSold2 + " sold");
}
}
```
这将在售票时更新标签的文本,以显示已售票的份数。
阅读全文