i've to retrieve the data from the textfile and display it into the JTable with two columns which name as "Expense" and "Amount". i already did one JTable but the outcome is not wat i wan..my Jtable table now is just one column with all the data.. i noe i need to have 2 dimensional array.. but i not sure where sld i place that.. pls help me.. thanks alot.. this is my coding so far:
String aLine ; Vector colExpense = new Vector(); Vector colAmt = new Vector(); Vector data = new Vector();
try {
File inputFile = new File("Expenses.txt");
FileInputStream in = new FileInputStream(inputFile); InputStreamReader reader = new InputStreamReader(in); BufferedReader br = new BufferedReader(reader);
// extract data while ((aLine = br.readLine()) != null) { StringTokenizer tokenizer1 = new StringTokenizer(aLine, "|"); Vector row = new Vector(); while(tokenizer1.hasMoreTokens()) { row.addElement(tokenizer1.nextToken()); } data.addElement( row ); } br.close(); } catch (Exception e) { e.printStackTrace(); }
// Create table using the DefaultTableModel model = new DefaultTableModel(data, colExpense); table = new JTable(model); JScrollPane scrollPane = new JScrollPane( table ); getContentPane().add( scrollPane ); JPanel buttonPanel = new JPanel(); getContentPane().add( buttonPanel, BorderLayout.SOUTH );
// Empty Row button JButton button1 = new JButton( "Add Empty Row" ); buttonPanel.add( button1 ); button1.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) { model.addRow( new Vector() ); } });
// Save table to file button JButton button2 = new JButton( "Save Table to File" ); buttonPanel.add( button2 ); button2.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Finish editing the current cell before saving if ( table.isEditing() ) { int row = table.getEditingRow(); int col = table.getEditingColumn(); table.getCellEditor(row, col).stopCellEditing(); }
int rows = table.getRowCount(); int columns = table.getColumnCount();
// Write out the Column Headers TableColumnModel header = table.getColumnModel(); for (int k = 0; k < columns; k++) { TableColumn column = header.getColumn(k); String value = (String)column.getHeaderValue(); System.out.print( value ); System.out.print( "|" ); }
System.out.println();
// Write out the table data for (int j = 0; j < rows; j++) { for (int k = 0; k < columns; k++) { String value = (String)table.getValueAt(j, k); System.out.print( value ); System.out.print( "|" ); } System.out.println(); } } }); }
public static void main(String[] args) { ViewExpense frame = new ViewExpense(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.pack(); frame.setVisible(true); } }