请根据如下要求编写一个java程序:实现多窗口卖票情况进度显示功能;界面上显示三个横向布局的小窗口,每个小窗口之间间隔开,小窗口的内容包括:(1)窗口名称为TXY_2_016_该窗口的编号(2)该窗口分配的票数(3)已卖票数;要求所有小窗口分配的票数总和等于16,每个小窗口每次卖出的票数由不大于5的随机数指定。添加一个按键,通过按键手动启动窗口卖票,之后在小窗口刷新每个窗口已卖票数。谢谢。
时间: 2024-02-17 11:05:25 浏览: 61
TSplitter.rar_对话框与窗口_Visual_C++_
好的,根据您的要求,我可以提供以下Java代码示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class TicketSeller extends JFrame implements ActionListener {
private JPanel panel;
private JLabel[] windowLabels;
private JLabel[] assignedLabels;
private JLabel[] soldLabels;
private JButton sellButton;
private static final int WINDOW_COUNT = 3;
private static final int TOTAL_TICKETS = 16;
private int[] assignedTickets;
private int[] soldTickets;
public TicketSeller() {
super("Ticket Seller");
panel = new JPanel();
panel.setLayout(new GridLayout(1, WINDOW_COUNT * 3, 10, 10));
windowLabels = new JLabel[WINDOW_COUNT];
assignedLabels = new JLabel[WINDOW_COUNT];
soldLabels = new JLabel[WINDOW_COUNT];
assignedTickets = new int[WINDOW_COUNT];
soldTickets = new int[WINDOW_COUNT];
Random rand = new Random();
int remainingTickets = TOTAL_TICKETS;
for (int i = 0; i < WINDOW_COUNT; i++) {
int tickets = rand.nextInt(5) + 1; // assign random tickets between 1-5
assignedTickets[i] = tickets;
remainingTickets -= tickets;
windowLabels[i] = new JLabel("TXY_2_016_" + (i + 1));
assignedLabels[i] = new JLabel("Assigned: " + tickets);
soldLabels[i] = new JLabel("Sold: " + soldTickets[i]);
panel.add(windowLabels[i]);
panel.add(assignedLabels[i]);
panel.add(soldLabels[i]);
}
// distribute remaining tickets randomly
for (int i = 0; i < remainingTickets; i++) {
int windowIndex = rand.nextInt(WINDOW_COUNT);
assignedTickets[windowIndex]++;
}
sellButton = new JButton("Sell Tickets");
sellButton.addActionListener(this);
Container container = getContentPane();
container.add(panel, BorderLayout.CENTER);
container.add(sellButton, BorderLayout.SOUTH);
setSize(500, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sellButton) {
Random rand = new Random();
for (int i = 0; i < WINDOW_COUNT; i++) {
int ticketsSold = rand.nextInt(assignedTickets[i] - soldTickets[i] + 1); // sell random tickets between 0-(assigned-sold)
soldTickets[i] += ticketsSold;
soldLabels[i].setText("Sold: " + soldTickets[i]);
}
}
}
public static void main(String[] args) {
TicketSeller seller = new TicketSeller();
seller.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
这段程序创建了一个名为 "Ticket Seller" 的窗口,其中包含三个小窗口,每个小窗口显示窗口名称、分配的票数和已卖票数。每个小窗口分配的票数总和为 16,每次卖出的票数由不大于5的随机数指定。还包括一个 "Sell Tickets" 按钮,按下之后会随机卖出每个窗口的一些票,并更新小窗口的已卖票数。
阅读全文