利用Java写一个三个窗口随机买票的程序
时间: 2024-05-13 22:17:00 浏览: 233
以下是基于Java Swing编写的随机买票程序:
```java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class TicketPurchase extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JLabel label1,label2,label3;
private JButton button;
private JTextField text1,text2,text3;
private ArrayList<String> tickets = new ArrayList<String>();
private String[] seatTypes = {"商务座","一等座","二等座","软卧","硬卧","硬座"};
private String[] ticketPrices = {"200元","150元","100元","180元","120元","80元"};
private Random random = new Random();
public TicketPurchase(){
setTitle("随机买票");
setSize(400,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(4,2));
label1 = new JLabel("商务座:");
label2 = new JLabel("一等座:");
label3 = new JLabel("二等座:");
button = new JButton("购买");
text1 = new JTextField();
text1.setEditable(false);
text2 = new JTextField();
text2.setEditable(false);
text3 = new JTextField();
text3.setEditable(false);
add(label1);
add(text1);
add(label2);
add(text2);
add(label3);
add(text3);
add(button);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == button){
tickets.clear();
for(int i=0; i<6; i++){
int randomNum = random.nextInt(10);
String ticket = seatTypes[i] + " " + ticketPrices[i] + " " + randomNum + "张";
tickets.add(ticket);
}
text1.setText(tickets.get(0));
text2.setText(tickets.get(1));
text3.setText(tickets.get(2));
}
}
public static void main(String[] args){
new TicketPurchase();
}
}
```
程序界面包含三个文本框和一个按钮,点击按钮即可随机生成三种票的信息(票种、价格、数量),并将信息显示在对应的文本框中。
阅读全文