Scrolling with JTables
I'm fairly new to building GUIs with Java. I'm trying to display the contents of a database table using a JTable object. The table has 13 columns. So I want the user to be able to scroll horizontally to see all the columns in the JTable object. Can anyone give me an example code segment that fits this scenario.
(All the data retrieval tasks are working fine. I just want the user to be able to scroll. The code I have written displays all the 13 columns in the viewable area of the JTable by reducing the column widths.)
Mount the JTable in a JScrollPane. Since JTable implements the Scrollable interface a parent scrollPane will have access to all the information it needs to properly show the table You can specify the preferred viewport size with the JTable setPreferredViewportSize method.
JTable table = yourTable
// provide a size hint
Dimension d = table.getPreferredSize();
d.width = as you like
d.height = ...
I would also like to know how to make the contents in a JTable read only.
Is there a way to programmatically select a row in a JTable? I want the first row of the table to be selected by default when the table loads.
Yes. You can do it through the tables SelectionModel or you can use the JTable convenience method
See api for use of the boolean flags.
changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)