wtf_are_my_initials wtf_are_my_initials - 2 months ago 19
Java Question

Java reorganizable grid

Is there any layout or library in Java to make GUIs that contain a list of data with separate items, and the rows can be reordered by clicking the top of the column. I'm sure that was a terrible job of explaining what I want, so here is a screenshot showing what I mean:

enter image description here

(taken from Spotify's desktop client, but you can find GUIs like this in all kinds of apps.)

Answer

How about a JTable?

Your criteria:

  • A list of data – yes. A table model can be as simple as an Object[][] or as complex as a custom class.
  • Reordering by clicking header – yes. You can use a TableRowSorter to sort when the column header is clicked.

For information on tables, see the "How to Use Tables" section of The Java Tutorial.

This document also has a section, "Sorting and Filtering", that talks about sorting with the column header. Here's an excerpt:

Table sorting and filtering is managed by a sorter object. The easiest way to provide a sorter object is to set autoCreateRowSorter bound property to true:

JTable table = new JTable();
table.setAutoCreateRowSorter(true);

This action defines a row sorter that is an instance of javax.swing.table.TableRowSorter. This provides a table that does a simple locale-specific sort when the user clicks on a column header. This is demonstrated in TableSortDemo.java, as seen in this screen shot:

TableSortDemo

More reference: