65919

JTable only displaying 1 row

Question:

I am trying to display part of a resultset in a JTable (Two columns), I can only manage to see one row. The JTable is in an existing GUI and the resultset is passed to a method in the GUI class. When I do a Vector size() it is returning one. This is telling me there is only one entry in the list. I should be seeing at 4 entries The entry I am seeing is the last one of what I expect would be 4.

Please see the method below: Any help would be much appreciated.

public static void getResultSet(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); //JTable name is resultsTable includes Scrollpane // names of columns Vector<String> columnNames = new Vector<String>(); int columnCount = 2; for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); System.out.println("ColumnNames "+columnNames ); } // data from the table // Vector<Vector<Object>> data = new Vector<Vector<Object>>(); Vector<Vector<String>> data = new Vector<Vector<String>>(); while (resultSet.next()) { Vector<String> vector = new Vector<String>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(resultSet.getString(columnIndex)); } data.add(vector); System.out.println("Vector Value = "+ data); System.out.println("Vector Size =" + data.size()); //Returning 1 - Should see 4 entries DefaultTableModel datamodel = new DefaultTableModel(data,columnNames); resultsTable.setModel(datamodel); }

Answer1:

<blockquote>

"This is telling me there is only one entry in the list. I should be seeing at 4 entries The entry I am seeing is the last one of what I expect would be 4."

</blockquote>

You're creating a new DefaultTableModel each iteration. Don't do that.

DefaultTableModel datamodel = new DefaultTableModel(data,columnNames); resultsTable.setModel(datamodel);

Take the above out. Instead, set the model first. Then just .addRow(row) in the loop

for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); System.out.println("ColumnNames "+columnNames ); } DefaultTableModel datamodel = new DefaultTableModel(columnNames, 0); table.setModel(datamodel); while (resultSet.next()) { Vector<String> vector = new Vector<String>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(resultSet.getString(columnIndex)); } datamodel.addRow(vector); }

The constructor for the DefaultTableModel(columnNames, 0) where 0 is the number of initial rows. So all you need to do is add rows dynamically one by one in the while(rs.next()). For each row of data you get in a Vector just datamodal.addRow(vector)

<hr />

<strong>UPDATE</strong>

Like I said, I don't know what you're doing wrong, but there's nothing wrong with my code. Here's a test program

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; public class TestTableModel { private ResultSet resultSet = null; public TestTableModel() throws SQLException { initDB(); JTable table = new JTable(getModel(resultSet)); JScrollPane scroll = new JScrollPane(table); JFrame frame = new JFrame("Test Table Model"); frame.add(scroll); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { TestTableModel testTableModel = new TestTableModel(); } catch (SQLException ex) { ex.printStackTrace(); } } }); } private DefaultTableModel getModel(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); Vector<String> columnNames = new Vector<>(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); System.out.println("ColumnNames " + columnNames); } DefaultTableModel dataModel = new DefaultTableModel(columnNames, 0); while (resultSet.next()) { Vector<String> vector = new Vector<>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(resultSet.getString(columnIndex)); } dataModel.addRow(vector); } return dataModel; } private void initDB() throws SQLException { Connection conn = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection( "jdbc:mysql://localhost/...", "...", "..."); ps = conn.prepareStatement("SELECT * FROM city"); resultSet = ps.executeQuery(); } catch (ClassNotFoundException | SQLException ex) { ex.printStackTrace(); } } }

<img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/5SnL1.png" data-original="https://i.stack.imgur.com/5SnL1.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

Recommend

  • DefaultTableModel in a JFrame only creating on Row - JAVA
  • How to get/set the cell value of a JTable by its column name
  • Non Intersecting two ResultSet in Java
  • Add a JScrollPane to a JFrame
  • Add a jfree bar chart into a scroll pane
  • Add user input data to an ArrayList and display it into a Jtable using custom a Tablemodel
  • List files and directories with Jtree and File in Java
  • iText PdfPTableEventForwarder not getting called when expected,
  • retrieving data from mysql and putting it on JTables
  • Scroll 2 listview at same time
  • How can I move the image in GUI
  • Dynamically Loading Project Online Properties via CSOM
  • rows not deleted from JTable
  • Unable to get Bootstrap Tooltip to display above div when inside scroll pane
  • How to stretch QTableView last column header
  • QComboBox and app.setStyle(“cleanlooks”)
  • JTable delete multiple rows with AbstractTableModel
  • How to make a cell behave like it's editable but have it read only?
  • Aligning and Inlining components (or icons) in JTextPane
  • How to customise JIDE grids in Matlab
  • Reading a file into a multidimensional array
  • App restarts from wrong activity
  • Groovy: Unexpected token “:”
  • Replace value with Factor in r data.table
  • Jetty Server not starting: Unable to establish loopback connection
  • How to access EntityManager inside Entity class in EJB3
  • Repeat a vertical line on every page in Report Builder / SSRS
  • sending/ receiving email in Java
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • Angular 2 constructor injection vs direct access
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • How does Linux kernel interrupt the application?
  • Sorting a 2D array using the second column C++
  • UserPrincipal.Current returns apppool on IIS
  • java string with new operator and a literal