rimsky
rimsky

Reputation: 1193

Dynamic JTable UI questions

I'd like to create a JTable with a UI similar to this:

enter image description here

where the "+" and "-" indicate buttons that add or remove the associated row or column. To ensure that the buttons align well with the existing rows and columns, it seems easiest to extend the table beyond the data portion to also include the buttons. So, the table above would have 5 rows and 6 columns.

Questions:

  1. Can I place buttons above the column headers in a JTable?
  2. My understanding is that I can't remove the cell borders for the buttons and blank cells (see here) at the cell level. Then, are there alternative ways to make the buttons align with the columns or rows?
  3. Are there similar UI styles you've seen or used that permit the desired behavior? Any libraries? I know this can be accomplished with, e.g., a combo box for choosing a particular row or column to be deleted. However, I'd prefer styles where the option to add/remove a row/column is placed immediately next to the row/column.

Thanks for your help.

Upvotes: 0

Views: 242

Answers (2)

Robin
Robin

Reputation: 36621

If you are open for alternative UI's: a JXTable from the SwingX project has a UI which allows to hide certain columns, or bring them back afterwards. This is of course only useful if you only want to hide/show existing columns. If you want to add brand-new columns, I am afraid that the SwingX UI is not sufficient.

For the adding/removal of rows, I would consider using a pop-up menu containing such actions. A bit similar to what Microsoft Excel offers. There you don't have a + or - sign either, but can find these actions by right clicking on the row number.

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347332

The short answer is (mostly) yes, the long answer, it's a bit of work.

I would take advantage of the JScrollPane's row header, see setRowHeader for more details.

enter image description here

(Picture used from the JavaDocs)

This will require you to layout your components to match the height of each row.

The table header is a little more complicated and comes down to whether this is a custom table implementation or not.

If you intent to extend JTable (or a sub component of), you should take a look into replacing the functionality of the configureEnclosingScrollPane (and corresponding unconfigureEnclosingScrollPane) method. This would allow you to wrap the JTableHeader in a custom component and set it to the scroll pane's column header position.

If not, you will need to adjust the scroll pane's column header yourself. Either way, the basic approach is the same.

You want a component, that can use the JTableHeader and provide you the means to layout out the components you want. I'd use something like a BorderLayout with the JTableHeader in the South position and your controls in the North

IMHO

Upvotes: 2

Related Questions