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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With