我有一个包含按钮和文本框的框架。
我的目的是从文本字段读取ID号,当单击按钮时,我的表应该显示该ID及其名称和标记。
我的"UserSearchFile.txt"是这样的:
12 joe 120
14 ted 220
19 alex 560
22 julia 668
我的jButton6ActionPerformed整个代码是这样的:
int idS=Integer.parseInt(jTextField2.getText());
final Vector data = new Vector();
final Vector column = new Vector();
File f=new File("D:\UserSearchFile.txt");
try{
FileReader fr=new FileReader(f);
BufferedReader br1=new BufferedReader(fr);
String s;
while ((s = br1.readLine()) != null) {
String[] st = s.split(" ");
String id = st[0];
String name = st[1];
String mark = st[2];
if (id.equals(String.valueOf(idS))) {
try {
String line2;
FileInputStream fis = new FileInputStream("D:\UserSearchFile.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br2.readLine(), " ");
while (st1.hasMoreTokens())
column.addElement(st1.nextToken());
while ((line2 = br2.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line2, " ");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (IOException ex) {
Logger.getLogger(MainFrame1.class.getName()).log(Level.SEVERE, null, ex);
}
jTable1.setModel(new AbstractTableModel() {
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return column.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
});
jTable1.setVisible(true);
请帮助我,告诉我如何写干净,简单。
首先为变量和方法使用有意义的名称。jTable1
, br1
, br2
和jButton6ActionPerformed
是不可接受的名称。
然后尝试将一个复杂的方法拆分为2或3个操作,其本身也拆分为2或3个操作,等等。每个操作都应该是一个方法调用。例如:
private void readButtonClicked() {
String id = idTextField.getText();
Student student = findStudentWithId(id);
showStudentInGUI(student);
}
private Student findStudentWithId(String id) {
List<String> lines = readLinesInFile();
List<Student> students = transformLinesIntoStudents(lines);
Student studentWithId = findStudentWithId(students, id);
}
private Student findStudentWithId(List<Student> students, String id) {
for (Student student : students) {
if (student.getId().equals(id)) {
return student;
}
}
return null;
}
private List<Student> transformLinesIntoStudents(List<String> lines) {
List<Student> students = new ArrayList<Student>(lines.size());
for (String line : lines) {
students.add(parseStudentLine(line);
}
return students;
}
...