Java编写一个图形界面的火车票售票程序,有三个窗口用来显示售票及余票信息,两个按钮,分别为 开始售票 和 退出系统 点击开始售票按钮 三个窗口同时进行售票 票售完时 弹出消息框 提示已售完 点击 退出系统按钮 系统退出
时间: 2024-02-22 07:55:30 浏览: 98
好的,以下是一个简单的Java程序,实现了你要求的功能:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TrainTicketSystem extends JFrame implements ActionListener {
private JLabel lblTicket1, lblTicket2, lblTicket3;
private JButton btnStart, btnExit;
private int ticket1 = 100, ticket2 = 100, ticket3 = 100;
public TrainTicketSystem() {
setTitle("火车票售票程序");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 3));
lblTicket1 = new JLabel("车次1余票:" + ticket1);
add(lblTicket1);
lblTicket2 = new JLabel("车次2余票:" + ticket2);
add(lblTicket2);
lblTicket3 = new JLabel("车次3余票:" + ticket3);
add(lblTicket3);
btnStart = new JButton("开始售票");
btnStart.addActionListener(this);
add(btnStart);
add(new JLabel());
add(new JLabel());
btnExit = new JButton("退出系统");
btnExit.addActionListener(this);
add(btnExit);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
new Thread(new TicketSeller(1)).start();
new Thread(new TicketSeller(2)).start();
new Thread(new TicketSeller(3)).start();
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
private class TicketSeller implements Runnable {
private int trainNo;
public TicketSeller(int trainNo) {
this.trainNo = trainNo;
}
public void run() {
while (true) {
synchronized (this) {
if (trainNo == 1 && ticket1 > 0) {
ticket1--;
lblTicket1.setText("车次1余票:" + ticket1);
} else if (trainNo == 2 && ticket2 > 0) {
ticket2--;
lblTicket2.setText("车次2余票:" + ticket2);
} else if (trainNo == 3 && ticket3 > 0) {
ticket3--;
lblTicket3.setText("车次3余票:" + ticket3);
} else {
JOptionPane.showMessageDialog(null, "车次" + trainNo + "已售完");
break;
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new TrainTicketSystem();
}
}
```
这个程序采用了多线程的方式进行售票,每个车次对应一个线程。点击开始售票按钮时,会启动三个线程去售票,当某个车次票已售完时,会弹出消息框提示。点击退出系统按钮时,程序会退出。
阅读全文