写一个java的swing程序,配置教师端的 ip 和端口信息,输入 学生学号和姓名,请求点名,将学生信息发送给教师端,发送成功后,收到教师 端发送来的确认消息,然后点名结束,关闭系统
时间: 2023-10-29 19:06:53 浏览: 69
好的,我了解您的要求了。以下是一个简单的Java Swing程序,用于配置教师端的IP和端口信息,输入学生学号和姓名,请求点名并将学生信息发送给教师端,接收教师端发送的确认消息并关闭系统:
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class RollCallSystem extends JFrame implements ActionListener {
private JTextField tfStudentID, tfName, tfIP, tfPort;
private JButton btnRollCall;
private JTextArea taMessage;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public RollCallSystem() {
setTitle("点名系统");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 400);
setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
panel.add(new JLabel("学号:"));
tfStudentID = new JTextField();
panel.add(tfStudentID);
panel.add(new JLabel("姓名:"));
tfName = new JTextField();
panel.add(tfName);
panel.add(new JLabel("教师端IP:"));
tfIP = new JTextField("127.0.0.1");
panel.add(tfIP);
panel.add(new JLabel("教师端端口:"));
tfPort = new JTextField("8888");
panel.add(tfPort);
panel.add(new JLabel());
btnRollCall = new JButton("点名");
btnRollCall.addActionListener(this);
panel.add(btnRollCall);
taMessage = new JTextArea();
taMessage.setEditable(false);
JScrollPane scrollPane = new JScrollPane(taMessage);
Container container = getContentPane();
container.add(panel, BorderLayout.NORTH);
container.add(scrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnRollCall) {
String studentID = tfStudentID.getText();
String name = tfName.getText();
String ip = tfIP.getText();
int port = Integer.parseInt(tfPort.getText());
try {
socket = new Socket(ip, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println(studentID + "," + name);
taMessage.append("已发送点名请求\n");
String response = in.readLine();
taMessage.append("收到教师端确认消息:" + response + "\n");
socket.close();
in.close();
out.close();
btnRollCall.setEnabled(false);
} catch (IOException ex) {
taMessage.append("连接教师端失败\n");
}
}
}
public static void main(String[] args) {
RollCallSystem frame = new RollCallSystem();
frame.setVisible(true);
}
}
```
这个程序使用了Java的Socket类来连接教师端,发送学生信息并接收确认消息。当用户点击“点名”按钮时,程序会尝试连接教师端,发送学生信息,接收确认消息,并关闭连接。如果连接失败,程序会提示用户连接失败。
阅读全文