用java写一个四个窗口同时售票的代码
时间: 2024-01-02 11:01:56 浏览: 90
以下是一个使用 Java 多线程和 GUI 组件实现的四个窗口同时售票的代码示例:
```java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TicketSeller {
private static final int NUM_OF_WINDOWS = 4; // 窗口数量
private final AtomicInteger ticketsRemaining = new AtomicInteger(100); // 剩余票数
private final JLabel remainingLabel = new JLabel("剩余票数:" + ticketsRemaining.get()); // 显示剩余票数的标签
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new TicketSeller().initGUI();
}
});
}
private void initGUI() {
JFrame frame = new JFrame("售票系统");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new GridLayout(NUM_OF_WINDOWS, 1));
for (int i = 0; i < NUM_OF_WINDOWS; i++) {
JPanel windowPanel = new JPanel(new FlowLayout());
JLabel windowLabel = new JLabel("售票窗口 " + (i + 1) + ":");
JButton sellButton = new JButton("售票");
sellButton.addActionListener(new SellButtonListener());
windowPanel.add(windowLabel);
windowPanel.add(sellButton);
mainPanel.add(windowPanel);
}
JPanel remainingPanel = new JPanel(new BorderLayout());
remainingPanel.add(remainingLabel, BorderLayout.WEST);
frame.add(mainPanel, BorderLayout.CENTER);
frame.add(remainingPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class SellButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int remaining = ticketsRemaining.get();
if (remaining > 0) {
ticketsRemaining.decrementAndGet();
remainingLabel.setText("剩余票数:" + ticketsRemaining.get());
}
}
}
}
```
该示例程序中,通过使用 `JFrame`、`JPanel`、`JLabel` 和 `JButton` 等 GUI 组件,创建了一个包含四个窗口和一个显示剩余票数的标签的界面。同时,使用 `AtomicInteger` 类型的 `ticketsRemaining` 变量来记录剩余票数,并通过 `SellButtonListener` 类实现了按钮的点击事件处理,当剩余票数大于 0 时,减少剩余票数并更新显示标签的内容。
需要注意的是,该示例程序仅作为参考,可能存在一些不足之处,具体实现方式可以根据实际需求进行优化和改进。
阅读全文