用java的gui写座位选择系统
时间: 2023-09-20 07:03:00 浏览: 63
好的,座位选择系统可以使用 Java 的 Swing 组件来实现 GUI 界面,以下是一个简单的座位选择系统的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class SeatSelectSystem {
private int rows, cols;
private boolean[][] seats;
private ArrayList<int[]> selectedSeats;
private JFrame frame;
private JPanel panel;
private JButton btnConfirm;
public SeatSelectSystem(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.seats = new boolean[rows][cols];
this.selectedSeats = new ArrayList<>();
this.frame = new JFrame("座位选择系统");
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.panel = new JPanel();
this.panel.setLayout(new GridLayout(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
JButton btnSeat = new JButton("(" + (i+1) + ", " + (j+1) + ")");
btnSeat.addActionListener(new SeatListener(i, j));
this.panel.add(btnSeat);
}
}
this.btnConfirm = new JButton("确定");
this.btnConfirm.addActionListener(new ConfirmListener());
this.frame.add(this.panel, BorderLayout.CENTER);
this.frame.add(this.btnConfirm, BorderLayout.SOUTH);
this.frame.pack();
this.frame.setVisible(true);
}
private class SeatListener implements ActionListener {
private int row, col;
public SeatListener(int row, int col) {
this.row = row;
this.col = col;
}
public void actionPerformed(ActionEvent e) {
if (!seats[row][col]) {
JButton btnSeat = (JButton) e.getSource();
btnSeat.setBackground(Color.GREEN);
seats[row][col] = true;
selectedSeats.add(new int[]{row, col});
} else {
JButton btnSeat = (JButton) e.getSource();
btnSeat.setBackground(null);
seats[row][col] = false;
selectedSeats.remove(new int[]{row, col});
}
}
}
private class ConfirmListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (selectedSeats.size() == 0) {
JOptionPane.showMessageDialog(frame, "您还未选择座位!", "错误", JOptionPane.ERROR_MESSAGE);
} else {
StringBuilder sb = new StringBuilder();
for (int[] seat : selectedSeats) {
sb.append("(").append(seat[0]+1).append(", ").append(seat[1]+1).append("), ");
}
String seatStr = sb.substring(0, sb.length()-2);
JOptionPane.showMessageDialog(frame, "您已成功选择座位:" + seatStr, "选座成功", JOptionPane.INFORMATION_MESSAGE);
}
}
}
public static void main(String[] args) {
SeatSelectSystem system = new SeatSelectSystem(5, 8);
}
}
```
这个座位选择系统使用了 Swing 的 JButton 组件来实现座位按钮,并在用户点击座位时改变按钮的背景颜色,同时记录用户选择的座位。用户点击“确定”按钮后,检查用户是否选择了座位,并将用户选择的座位信息以弹窗形式展示给用户。