Yohanes Setiawan
Yohanes Setiawan

Reputation: 81

JTable Header Suddenly Changed its Column Name

I have designed jtable like this:

enter image description here

And when I compiled my Java GUI Netbeans program, it has no problem:

enter image description here

But after I press a JButton that I used this code to upload excel:

 private void b_browseActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    int column, row;
    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(this);
    File file = chooser.getSelectedFile();
    chooser.setFileFilter(new FileNameExtensionFilter("Excel File", "xls"));
    String al = file.getAbsolutePath();
    File excelFile = new File(al);
    if(!file.getName().endsWith("xls")){
 JOptionPane.showMessageDialog(null, 
   "Pilih file Excel (.xls) saja!",
   "Error",JOptionPane.ERROR_MESSAGE);
}
else
{
 if (excelFile.exists()) {
    try {
        Workbook workbook = Workbook.getWorkbook(excelFile);
        Sheet sheet = workbook.getSheets()[0];
        TableModel model = new DefaultTableModel(sheet.getRows(), sheet.getColumns());
        DefaultTableModel model2 = new DefaultTableModel(null, JdlTabel);
        for (row = 0; row < sheet.getRows(); row++) {
            for ( column = 0; column < sheet.getColumns(); column++) {
                String content = sheet.getCell(column, row).getContents();
                model.setValueAt(content, row, column);
                data[row][column]=Double.parseDouble(content);
                n_data = sheet.getRows();
                k_data = sheet.getColumns(); 

            }
        }
        j_latih.setModel(model2);
        j_latih.setModel(model); //input data to Jtable
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error : " + e);
        e.printStackTrace();
    }

 } else {
    JOptionPane.showMessageDialog(null, "There is no data!"); }
}  
    cek_kmeans=0;
    cek_data=1;//control tombol      
}                                        

suddenly the table columns name changed like this:

enter image description here

So, what's wrong? How do I fix this?

Upvotes: 0

Views: 74

Answers (1)

camickr
camickr

Reputation: 324157

JTable Header Suddenly Changed its Column Name

DefaultTableModel model2 = new DefaultTableModel(null, JdlTabel);

You specify "null" for the column headers when you recreate the table model. so the default headings are used.

The solution is to either:

  1. use the original column names when you recreate the model.
  2. Don't recreate the entire model. Instead you can remove all the rows from the current model using setRowCount(0) of your DefaultTableModel. Then you use theaddRow(...)method of theDefaultTableModel` to load the data back into the model one row at a time.

Upvotes: 1

Related Questions