最近提出的一个问题:如何在“详细信息”视图中启动 JFileChooser?并且 answer 提供了一种很好的技术来做到这一点。
我想将这里的愿望提高一级:鉴于我现在知道如何在详细信息视图中打开 JFileChooser,我可以也让它打开按日期排序的文件吗?我知道用户当然可以单击标题,但是有没有办法在代码中实现这一点?
我不知道有任何 API 可以做到这一点。以下代码查找文件选择器使用的表,然后手动对日期列进行排序:
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);
您还需要 Darryl 的 Swing Utils 课程。
编辑:
显然在更高版本中更改了一些逻辑,如下面评论中所建议:
尝试:
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);
这会将排序顺序的切换添加到事件调度线程 (EDT) 的末尾,因此它应该在 JTable 详细信息视图的默认行为之后执行。
只需重写 ShowDialog 方法之一:
JFileChooser jFileChooser= new JFileChooser(){
public JTable jt;
private JDialog dialog = null;
private int returnValue = ERROR_OPTION;
@Override
public int showDialog(Component parent, String approveButtonText)
throws HeadlessException {
if (dialog != null) {
// Prevent to show second instance of dialog if the previous one still exists
return JFileChooser.ERROR_OPTION;
}
if(approveButtonText != null) {
setApproveButtonText(approveButtonText);
setDialogType(CUSTOM_DIALOG);
}
dialog = createDialog(parent);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
returnValue = CANCEL_OPTION;
}
});
returnValue = ERROR_OPTION;
rescanCurrentDirectory();
jt = SwingUtils.getDescendantsOfType(JTable.class, this).get(0);
jt.getRowSorter().toggleSortOrder(3);
jt.getRowSorter().toggleSortOrder(3);
dialog.show();
firePropertyChange("JFileChooserDialogIsClosingProperty", dialog, null);
// Remove all components from dialog. The MetalFileChooserUI.installUI() method (and other LAFs)
// registers AWT listener for dialogs and produces memory leaks. It happens when
// installUI invoked after the showDialog method.
dialog.getContentPane().removeAll();
dialog.dispose();
dialog = null;
return returnValue;
}
};