Reputation: 58
I successfully populated my JTable
with the contents of my database table but I only want to show selected columns of it. Is there any way of doing this? Or is it even possible to select which column to display in a JTable
?
Here is the method of populating my JTable
private void Update_table() {
try {
String sql = "select * from Members";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
Members_Table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
My database table name is "Members". "Members_Table" is the name of my JTable
.
Upvotes: 0
Views: 2843
Reputation: 5937
If you're looking for a bit more robust data model on the Java side and want to hide the columns in the JTable, you can use removeColumn from JTable. This does not remove the column from the Table model, only from visible presentation. If you keep track of which columns are hidden or visible, you can easily put the column back in, and its data will still be properly associated.
For example, to remove the first column, you could use:
myTable.removeColumn(myTable.getColumnModel().get(0));
// i don't remember if it's 0-index or 1-index for first column
As an example, I would dynamically fill a JPanel with checkboxes for each column and then checking and unchecking individual boxes would hide and disable those columns. This allows you to keep all the data, but only present those relevant to the user at the time, similar to how hiding columns in Excel works.
Upvotes: 1
Reputation: 1639
You could try changing your sql statement to only select the columns you are interested in. For instance, if Members has the columns "MemberId", "MemberFirstName", "MemberLastName" "MemberAddressFK", and you only wanted to display MemberFirstName and MemberLastName, you could change your sql to be
String sql = "select MemberFirstName, MemberLastName from Members";
You can find more details about the sql select statement at http://beginner-sql-tutorial.com/sql-select-statement.htm
Upvotes: 2