写一个完整的JAVA程序 题为: 多窗口卖票情况进度显示: (1)使用Panel类显示三个窗口的卖票情况, 第一个窗口名称为CY_1_104_1,窗口上显示分配的票数为30张,显示已卖票数(用进度条加数字显示) 第二个窗口名称为CY_1_104_2,窗口上显示分配的票数为32张,显示已卖票数(用进度条加数字显示) 第三个窗口名称为CY_1_104_3,窗口上显示分配的票数为42张,显示已卖票数(用进度条加数字显示) (2)所有窗口分配的票数总和等于104,每个窗口每次卖出的票数由随机数指定 (3)启动卖票行为,由每次通过自动按钮一键完成,窗口的每次卖票间隔为2秒。
时间: 2024-02-17 15:04:48 浏览: 72
以下是一个实现多窗口卖票情况进度显示的 JAVA 程序:
```java
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class TicketSelling extends JFrame {
private static final int TOTAL_TICKETS = 104;
private static final int[] TICKETS_PER_WINDOW = {30, 32, 42};
private static final String[] WINDOW_NAMES = {"CY_1_104_1", "CY_1_104_2", "CY_1_104_3"};
private final JPanel[] windowPanels;
private final JProgressBar[] progressBars;
private final JLabel[] soldLabel;
private final Random random = new Random();
public TicketSelling() {
super("Ticket Selling Progress");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
windowPanels = new JPanel[TICKETS_PER_WINDOW.length];
progressBars = new JProgressBar[TICKETS_PER_WINDOW.length];
soldLabel = new JLabel[TICKETS_PER_WINDOW.length];
for (int i = 0; i < TICKETS_PER_WINDOW.length; i++) {
windowPanels[i] = new JPanel(new BorderLayout());
windowPanels[i].setPreferredSize(new Dimension(300, 100));
JPanel progressBarPanel = new JPanel(new BorderLayout());
progressBars[i] = new JProgressBar(0, TICKETS_PER_WINDOW[i]);
progressBarPanel.add(progressBars[i], BorderLayout.CENTER);
soldLabel[i] = new JLabel("0/" + TICKETS_PER_WINDOW[i]);
progressBarPanel.add(soldLabel[i], BorderLayout.EAST);
windowPanels[i].add(progressBarPanel, BorderLayout.CENTER);
windowPanels[i].add(new JLabel(WINDOW_NAMES[i]), BorderLayout.NORTH);
add(windowPanels[i]);
}
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void startSelling() {
new Thread(() -> {
while (true) {
int windowIndex = random.nextInt(TICKETS_PER_WINDOW.length);
if (progressBars[windowIndex].getValue() < TICKETS_PER_WINDOW[windowIndex]) {
progressBars[windowIndex].setValue(progressBars[windowIndex].getValue() + 1);
soldLabel[windowIndex].setText(progressBars[windowIndex].getValue() + "/" + TICKETS_PER_WINDOW[windowIndex]);
}
int totalSold = 0;
for (int i = 0; i < TICKETS_PER_WINDOW.length; i++) {
totalSold += progressBars[i].getValue();
}
setTitle("Ticket Selling Progress - Total: " + totalSold + "/" + TOTAL_TICKETS);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public static void main(String[] args) {
TicketSelling ticketSelling = new TicketSelling();
ticketSelling.startSelling();
}
}
```
该程序使用了 `JFrame` 和 `JPanel` 进行多窗口的显示,并使用了 `JProgressBar` 和 `JLabel` 显示每个窗口的卖票情况和总体卖票情况。程序通过随机数模拟每个窗口的卖票行为,并在每次卖票后更新卖票情况显示。程序通过 `Thread.sleep(2000)` 控制每个窗口的卖票间隔为 2 秒,并且在窗口标题中显示总体卖票情况。程序通过 `TicketSelling.main()` 方法启动并运行。
阅读全文