请根据如下要求编写并解释一个java程序:实现多窗口卖票情况进度显示功能;界面上显示三个横向布局的小窗口,每个小窗口之间间隔开,要求窗口界面很大;小窗口的内容包括:(1)窗口名称为TXY_2_216_该窗口的编号(2)该窗口分配的票数(3)已卖票数;要求所有小窗口分配的票数总和等于216,每个小窗口每次卖出的票数由不大于72的随机数指定。添加一个按键,通过按键手动启动窗口卖票,之后在小窗口刷新每个窗口已卖票数。谢谢。
时间: 2024-02-18 11:59:15 浏览: 21
以下是一个简单的Java程序实现多窗口卖票情况进度显示功能:
```java
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class TicketSales extends JFrame {
private JPanel panel;
private JLabel[] windowLabels;
private JLabel[] ticketLabels;
private JLabel[] soldLabels;
private JButton button;
private int[] tickets;
private int[] soldTickets;
public TicketSales() {
super("多窗口卖票情况进度显示");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel(new GridLayout(1, 3, 10, 0));
windowLabels = new JLabel[3];
ticketLabels = new JLabel[3];
soldLabels = new JLabel[3];
tickets = new int[] {72, 72, 72};
soldTickets = new int[] {0, 0, 0};
for (int i = 0; i < 3; i++) {
windowLabels[i] = new JLabel("TXY_2_216_" + (i + 1));
ticketLabels[i] = new JLabel("剩余票数:" + tickets[i]);
soldLabels[i] = new JLabel("已售票数:" + soldTickets[i]);
JPanel windowPanel = new JPanel(new GridLayout(3, 1));
windowPanel.add(windowLabels[i]);
windowPanel.add(ticketLabels[i]);
windowPanel.add(soldLabels[i]);
panel.add(windowPanel);
}
button = new JButton("卖票");
button.addActionListener(e -> sellTickets());
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
add(panel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
setSize(800, 200);
setVisible(true);
}
private void sellTickets() {
Random random = new Random();
for (int i = 0; i < 3; i++) {
int num = random.nextInt(73);
if (num <= tickets[i]) {
soldTickets[i] += num;
tickets[i] -= num;
} else {
soldTickets[i] += tickets[i];
tickets[i] = 0;
}
ticketLabels[i].setText("剩余票数:" + tickets[i]);
soldLabels[i].setText("已售票数:" + soldTickets[i]);
}
}
public static void main(String[] args) {
new TicketSales();
}
}
```
该程序使用了Java的Swing GUI库来创建窗口和小窗口,并使用GridLayout布局将三个小窗口放置在一个面板中。程序还通过一个数组来跟踪每个小窗口的票数和已售票数,并使用一个随机数生成器来模拟售票过程。当用户点击“卖票”按钮时,程序将随机生成每个小窗口卖出的票数,并更新小窗口的票数和已售票数标签。
在该程序中,每个小窗口分配的票数都是相同的,总票数为216,因此每个小窗口都分配了72张票。程序使用一个数组来存储每个小窗口的票数和已售票数,并通过计算每个小窗口的剩余票数和已售票数来更新小窗口的标签。程序还使用了一个随机数生成器来模拟售票过程,并在用户点击“卖票”按钮时更新小窗口的标签。
阅读全文