1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| import javax.swing.*; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException;
public class Main { public static void main(String[] args) { JFrame frame = new JFrame("学生成绩输入"); frame.setSize(300, 150); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(); frame.add(panel); placeComponents(panel);
frame.setVisible(true); }
private static void placeComponents(JPanel panel) { panel.setLayout(null);
JLabel userLabel = new JLabel("用户名:"); userLabel.setBounds(10, 20, 80, 25); panel.add(userLabel);
JTextField userText = new JTextField(20); userText.setBounds(100, 20, 165, 25); panel.add(userText);
JLabel scoreLabel = new JLabel("清除:"); scoreLabel.setBounds(10, 50, 80, 25); panel.add(scoreLabel);
JTextField scoreText = new JTextField(20); scoreText.setBounds(100, 50, 165, 25); panel.add(scoreText);
JButton submitButton = new JButton("提交"); submitButton.setBounds(10, 80, 80, 25); panel.add(submitButton);
JButton clearButton = new JButton("清除"); clearButton.setBounds(180, 80, 80, 25); panel.add(clearButton);
submitButton.addActionListener(e -> { final var name = userText.getText(); final var score = scoreText.getText();
if (checkFormat(name, score)) { try { writeToFile(name, name); JOptionPane.showMessageDialog(panel, "写入成功!"); } catch (IOException e1) { JOptionPane.showMessageDialog(panel, "写入文件失败!"); } } else { JOptionPane.showMessageDialog(panel, "用户名或者成绩输入不合法"); } });
clearButton.addActionListener(e -> { userText.setText(""); scoreText.setText(""); }); }
private static boolean checkFormat(String username, String score) { if(username.isEmpty() || score.isEmpty()){ return false; } for (int i = 0; i < score.length(); i++) { if (!Character.isDigit(score.charAt(i))) { return false; } } return true; }
private static void writeToFile(String username, String score) throws IOException { FileWriter fileWriter = new FileWriter("scores.txt",true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.append("用户名:").append(username).append("\n"); bufferedWriter.append("成绩:").append(score).append("\n"); bufferedWriter.close(); } }
|