0

I'm reading in a file and want to output it to a jTable for viewing and editing. When I try to add rows the the DefaultTableModel the model is always empty for some reason. Any help/direction would be greatly appreciated. Thanks!

public class ReadFileGUI extends javax.swing.JFrame {

public static String file;
private DefaultTableModel model = new DefaultTableModel();

public ReadFileGUI() {
    initComponents();
}

 @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jButton1 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable(model);

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);


    jButton1.setText("Test");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jScrollPane1.setViewportView(jTable1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(14, 14, 14)
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGap(0, 0, Short.MAX_VALUE))
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

        String line = "Hello~There~This~Is~A~Test";
        String datavalue[] = line.split("~");                            
        Vector v = new Vector(Arrays.asList(datavalue));

        model.addRow(v);                  
        jTable1.tableChanged(new TableModelEvent(model));   
}

public static void main(String args[]) {

    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ReadFileGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ReadFileGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ReadFileGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ReadFileGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new ReadFileGUI().setVisible(true);
        }
    });
}    

private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;

}

Tai
  • 63
  • 2
  • 7
  • 1
    How and where are you checking that the model is empty? – Jim Apr 20 '12 at 16:14
  • Did you check the input file and the while loop is actually reading lines? – evanwong Apr 20 '12 at 16:15
  • Yes. datavalue[] contains 190 elements. When I check the model via debugger Model-> Data Vector -> Vector[1] -> size = 0. Likewise, checking the table Table->Table Header -> table -> dataModel -> dataVector ->[0] = size = 0 – Tai Apr 20 '12 at 16:29

1 Answers1

3

Here an updated version of your code which seems to work

import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Vector;

public class ReadFileGUI extends javax.swing.JFrame {
  private DefaultTableModel tableModel = new DefaultTableModel();
  private javax.swing.JButton populateTableButton;
  private javax.swing.JScrollPane tableScrollPane;
  private javax.swing.JTable table;

  public ReadFileGUI() {
    initComponents();
    setDefaultCloseOperation( javax.swing.WindowConstants.EXIT_ON_CLOSE);
  }

  @SuppressWarnings("unchecked")
  private void initComponents() {
    populateTableButton = new javax.swing.JButton();
    tableScrollPane = new javax.swing.JScrollPane();
    table = new javax.swing.JTable( tableModel );

    populateTableButton.setText( "Test" );
    populateTableButton.addActionListener( new ActionListener() {
      @Override
      public void actionPerformed( ActionEvent evt ) {
        populateTable();
      }
    } );

    tableScrollPane.setViewportView( table );

    getContentPane().setLayout( new BorderLayout(  ) );
    getContentPane().add( tableScrollPane, BorderLayout.CENTER );
    getContentPane().add( populateTableButton, BorderLayout.SOUTH );
    pack();
  }


  private void populateTable( ) {
    String line = "Hello~There~This~Is~A~Test";
    String dataValue[] = line.split("~");
    Vector<String> v = new Vector<>( Arrays.asList( dataValue ));
    tableModel.setColumnCount( v.size() );
    tableModel.addRow( v );
  }

  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        new ReadFileGUI().setVisible(true);
      }
    });
  }         
}

Things I changed:

  • used imports instead of full names to avoid horizontal scroll bars
  • used a BorderLayout iso generated layout to shorten the code
  • renamed some variables for improved readability of the code
  • removed the jTable1.tableChanged(new TableModelEvent(model)); call as the DefaultTableModel will fire the appropriate events when you use the addRow method. No need to indicate this change another time to the table

But the relevant change is the tableModel.setColumnCount( v.size() ); call. The default constructor of DefaultTableModel creates a model with zero columns and rows. If you first set the number of columns, you can use the addRow method

Robin
  • 36,233
  • 5
  • 47
  • 99
  • Thanks Robin! Did not know about the zero columns and rows part of DefaultTableModel. – Tai Apr 20 '12 at 19:40
  • @Tai after a quick look in the source code it just seems that all the correct events are fired, the row is added, but the number of columns is not updated, so the `TableModel#getColumnCount` still returns 0, hence nothing is visualized. The call to `setColumnCount` fixes that problem – Robin Apr 20 '12 at 19:44