Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a JFileChooser with files ordered by date

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?

like image 202
user1359010 Avatar asked May 07 '13 22:05

user1359010


1 Answers

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.

like image 129
camickr Avatar answered Sep 22 '22 18:09

camickr