用Java代码完成以下任务 多窗口卖票情况进度显示: (1)界面上显示两个以上的窗口卖票情况, 每个窗口内容包括 1.窗口名称是 LK _2_215_1 2.该窗口分配的票数,3.已卖票数(用进度条加数字显示) (2)所有窗口分配的票数总和等于215,每个窗口每次卖出的票数由随机数指定, (3)启动卖票行为,由每次通过按键手工启动
时间: 2024-02-17 22:05:04 浏览: 66
好的,以下是Java代码实现多窗口卖票情况进度显示的示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TicketSellerGUI {
private static final int TICKETS_NUM = 215; // 总票数
private static final int WINDOW_NUM = 2; // 窗口数量
private JFrame mainFrame;
private JPanel[] windowPanels;
private JLabel[] windowLabels;
private JProgressBar[] windowProgressBars;
private JButton sellButton;
public TicketSellerGUI() {
initialize();
}
private void initialize() {
// 创建主窗口
mainFrame = new JFrame("多窗口卖票情况进度显示");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(400, 200);
// 创建窗口面板数组
windowPanels = new JPanel[WINDOW_NUM];
windowLabels = new JLabel[WINDOW_NUM];
windowProgressBars = new JProgressBar[WINDOW_NUM];
// 创建窗口面板,并添加窗口名称、票数和进度条组件
for (int i = 0; i < WINDOW_NUM; i++) {
windowPanels[i] = new JPanel(new GridLayout(3, 1));
windowLabels[i] = new JLabel("LK_2_215_" + (i + 1));
windowPanels[i].add(windowLabels[i]);
int ticketsPerWindow = TICKETS_NUM / WINDOW_NUM;
if (i == WINDOW_NUM - 1) {
ticketsPerWindow += TICKETS_NUM % WINDOW_NUM;
}
windowLabels[i].setText(windowLabels[i].getText() + "(分配票数:" + ticketsPerWindow + ")");
windowProgressBars[i] = new JProgressBar(0, ticketsPerWindow);
windowProgressBars[i].setValue(0);
windowProgressBars[i].setStringPainted(true);
windowPanels[i].add(windowProgressBars[i]);
mainFrame.add(windowPanels[i]);
}
// 创建卖票按钮,并添加事件监听器
sellButton = new JButton("卖票");
sellButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sellTickets();
}
});
mainFrame.add(sellButton, BorderLayout.SOUTH);
mainFrame.setVisible(true);
}
private void sellTickets() {
sellButton.setEnabled(false); // 禁用卖票按钮
new Thread(new Runnable() {
@Override
public void run() {
int ticketsSold = 0;
while (ticketsSold < TICKETS_NUM) {
// 遍历所有窗口
for (int i = 0; i < WINDOW_NUM; i++) {
// 每个窗口随机卖出1-5张票
int sold = (int) (Math.random() * 5) + 1;
if (ticketsSold + sold > TICKETS_NUM) {
sold = TICKETS_NUM - ticketsSold;
}
// 更新已卖票数和进度条
synchronized (windowProgressBars[i]) {
int value = windowProgressBars[i].getValue() + sold;
windowProgressBars[i].setValue(value);
windowProgressBars[i].setString(value + "/" + windowProgressBars[i].getMaximum());
}
ticketsSold += sold;
if (ticketsSold >= TICKETS_NUM) {
break;
}
}
try {
// 休眠一段时间,模拟卖票过程
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sellButton.setEnabled(true); // 启用卖票按钮
}
}).start();
}
public static void main(String[] args) {
new TicketSellerGUI();
}
}
```
这个示例程序使用了Java Swing框架,实现了一个界面上显示两个窗口卖票情况的程序。在程序启动时,创建了两个窗口面板,每个面板包括窗口名称、票数和进度条组件。在卖票按钮的事件监听器中,使用多线程来模拟卖票过程。每个线程遍历所有窗口,每个窗口随机卖出1-5张票,并更新已卖票数和进度条。同时使用synchronized关键字来实现线程同步,防止多个窗口同时卖出同一张票的情况。当所有票都卖完后,卖票按钮重新启用。
阅读全文