用Java代码完成以下任务 二个窗口卖票情况进度显示: (1)分出两个窗口。第一个窗口分配的票数是107,窗口名称是LK _2_215_1。第二个窗口分配的票数是108,窗口名称是LK _2_215_2. 每个窗口内容包括 1.窗口名称,2.该窗口分配的票数,3.已卖票数(用进度条加数字显示) (2)每个窗口每次卖出的票数由随机数指定, (3)启动卖票行为,由每次通过按键手工启动
时间: 2024-02-18 13:58:55 浏览: 93
以下是Java代码实现:
```java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class TicketSellingSystem implements ActionListener {
private JFrame frame;
private JPanel panel1, panel2;
private JLabel label1, label2, label3, label4;
private JProgressBar progressBar1, progressBar2;
private JButton button;
private int ticket1 = 107, ticket2 = 108, sold1 = 0, sold2 = 0;
private Random random;
public TicketSellingSystem() {
random = new Random();
// 创建窗口1
panel1 = new JPanel();
label1 = new JLabel("LK _2_215_1");
label2 = new JLabel("票数:" + ticket1);
label3 = new JLabel("已卖票数:" + sold1);
progressBar1 = new JProgressBar(0, ticket1);
progressBar1.setStringPainted(true);
panel1.add(label1);
panel1.add(label2);
panel1.add(label3);
panel1.add(progressBar1);
// 创建窗口2
panel2 = new JPanel();
label1 = new JLabel("LK _2_215_2");
label2 = new JLabel("票数:" + ticket2);
label3 = new JLabel("已卖票数:" + sold2);
progressBar2 = new JProgressBar(0, ticket2);
progressBar2.setStringPainted(true);
panel2.add(label1);
panel2.add(label2);
panel2.add(label3);
panel2.add(progressBar2);
// 创建按钮
button = new JButton("卖票");
button.addActionListener(this);
// 创建主窗口
frame = new JFrame("卖票系统");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.add(panel2);
frame.add(button);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.pack();
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
// 窗口1卖票
if (sold1 < ticket1) {
int count = random.nextInt(5) + 1; // 每次卖出1-5张票
if (sold1 + count > ticket1) {
count = ticket1 - sold1;
}
sold1 += count;
progressBar1.setValue(sold1);
progressBar1.setString(sold1 + "/" + ticket1);
label3.setText("已卖票数:" + sold1);
}
// 窗口2卖票
if (sold2 < ticket2) {
int count = random.nextInt(5) + 1; // 每次卖出1-5张票
if (sold2 + count > ticket2) {
count = ticket2 - sold2;
}
sold2 += count;
progressBar2.setValue(sold2);
progressBar2.setString(sold2 + "/" + ticket2);
label3.setText("已卖票数:" + sold2);
}
}
}
public static void main(String[] args) {
new TicketSellingSystem();
}
}
```
运行程序后,会出现一个卖票系统的窗口,其中包含两个窗口和一个卖票按钮。每次点击按钮,程序会随机卖出1-5张票,直到两个窗口的票都卖完为止。每个窗口显示窗口名称、票数和已卖票数,进度条和数字显示已卖票数的进度情况。
阅读全文