7

A recent question asked: How can I start the JFileChooser in the Details view? and the answer provided a nice technique for doing that.

I'd like to raise the aspiration here one level: given that I now know how to open the JFileChooser in details view, can I also get it to open with the files ordered by date? I know the user can of course click on the headings, but is there a way to make this happen in the code?

Community
  • 1
  • 1
user1359010
  • 243
  • 3
  • 11

1 Answers1

7

I don't know of any API to do this. The following code finds the table used by the file chooser and then manually does the sort on the date column:

JFrame frame = new JFrame();
JFileChooser  fileChooser = new JFileChooser(".");
Action details = fileChooser.getActionMap().get("viewTypeDetails");
details.actionPerformed(null);

//  Find the JTable on the file chooser panel and manually do the sort

JTable table = SwingUtils.getDescendantsOfType(JTable.class, fileChooser).get(0);
table.getRowSorter().toggleSortOrder(3);

fileChooser.showOpenDialog(frame);

You will also need Darryl's Swing Utils class.

Edit:

Apparently some logic was changed in a later version as suggested in a comment below:

Try:

JTable table = SwingUtils.getDescendantsOfType(JTable.class, fileChooser).get(0);
table.getModel().addTableModelListener( new TableModelListener()
{
    @Override
    public void tableChanged(TableModelEvent e)
    {
        table.getModel().removeTableModelListener(this);
        SwingUtilities.invokeLater( () -> table.getRowSorter().toggleSortOrder(3) );
    }
});

fileChooser.showOpenDialog(frame);

This will add the toggling of the sort order to the end of the Event Dispatch Thread (EDT) so it should execute after the default behaviour of the JTable details view.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Unfortunately, this no longer worked at least from Java 11 due to this change in the `DetailsTableRowSorter`: https://github.com/openjdk/jdk/commit/458f8d25976b2d59b0c0b6cb89bbdadbbf9265ea `modelStructureChanged()` called `setSortKeys(null)` which effectively removes any sortings and this callback is called during making a list of files, at least on Linux. – Mingun Jul 01 '21 at 10:06
  • Yes, it works, but: (1) on Linux table has only 3 columns (`Type` column is missing), so you should use `toggleSortOrder(2)` on Linux; (2) it will always start from ASCENDING order – Mingun Jul 02 '21 at 10:29
  • repeat the toggleSortOrder line to start in DESCENDING order – Luciano Gonçalves Nov 05 '21 at 12:09