i have a frame that contain a button and textfield.
my porpuse is read ID number frome textfield and when clicked on button, my table should display that ID with its name and mark.
my “UserSearchFile.txt” is this:
12 joe 120
14 ted 220
19 alex 560
22 julia 668
my jButton6ActionPerformed whole code is this:
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);
please help me and tell me how to write cleany and simple.
Start by using meaningful names for your variables and methods.
jTable1,br1,br2andjButton6ActionPerformedare not acceptable names.Then try to split a complex method into 2 or three operations, themselves split into 2 or three operations, etc. Each operation should be a method call. For example: