Home >Java >javaTutorial >Why Does My JTable Show Duplicate Rows Despite Correct Data in My Data Model?
Despite having a correct data model with appropriate data, populating a JTable may result in each row containing duplicate values, raising concerns about the data integrity.
Initially, the suspicion falls on the custom data model, CollectionDataModel. The populate() method method appears to be behaving as intended, clearing existing data and populating it with the items in the collection, each stored in an ArrayList
To properly populate a JTable, the following considerations should be kept in mind:
The JTable population issue may arise if the data model or JTable implementation is incorrectly updated. The JTable may not be correctly utilizing the data model's methods, leading to incorrect population.
To resolve the issue, carefully review the CollectionDataModel implementation to ensure it conforms to the contract. Additionally, inspect the JTable implementation to verify that it is correctly using the data model's methods to populate its rows and columns.
Consider the following example that demonstrates proper JTable population:
import java.awt.EventQueue; import java.awt.GridLayout; import java.util.Map; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; public class EnvTableTest extends JPanel { public EnvTableTest() { this.setLayout(new GridLayout()); this.add(new JScrollPane(new JTable(new EnvDataModel()))); } private static class EnvDataModel extends AbstractTableModel { private Map<String, String> data = System.getenv(); private String[] keys; public EnvDataModel() { keys = data.keySet().toArray(new String[data.size()]); } @Override public String getColumnName(int col) { if (col == 0) { return "Key"; } else { return "Value"; } } @Override public int getColumnCount() { return 2; } @Override public int getRowCount() { return data.size(); } @Override public Object getValueAt(int row, int col) { if (col == 0) { return keys[row]; } else { return data.get(keys[row]); } } } private void display() { JFrame f = new JFrame("EnvTableTest"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(this); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new EnvTableTest().display(); } }); } }
In this example, the EnvDataModel custom data model correctly retrieves data from the environment variables and provides it to the JTable, resulting in a properly populated table.
The above is the detailed content of Why Does My JTable Show Duplicate Rows Despite Correct Data in My Data Model?. For more information, please follow other related articles on the PHP Chinese website!