setSelectedFile(文件文件)不在JFileChooser的GUI中显示选择

时间:2015-11-26 19:20:52

标签: java swing jfilechooser

以下代码将“pom.xml”打印到控制台。但它不会在GUI中标记所选文件,就像用户使用鼠标一样。

那么如何以编程方式选择并突出显示所选文件?

JFileChooser fc = new JFileChooser();

FileFilter filter = new FileNameExtensionFilter("POM",
        new String[] { "xml" });
fc.setAcceptAllFileFilterUsed(false);
fc.setFileFilter(filter);
fc.setCurrentDirectory(new File("./"));

fc.setSelectedFile(new File("pom.xml"));
System.out.println(fc.getSelectedFile());

fc.showOpenDialog(null);

这是代码:

enter image description here

但我希望看到选择:

enter image description here

1 个答案:

答案 0 :(得分:3)

这是一个有趣的问题,也可能取决于Look&感觉(L& F)使用。我在Windows上使用Metal L& F进行了测试。 JFileChooser类似乎没有正确处理最初选择的文件的视觉选择。

JFileChooser.ensureFileIsVisible方法中,更改当前目录(如有必要),并调用ensureFileIsVisible方法。在我的情况下,此方法最终调用sun.swing.FilePane.ensureFileIsVisible方法,该方法似乎确保所选文件滚动到用于显示文件的JListJTable中的视图中。但是,当我查看调试器发生的情况时,此时文件列表似乎未初始化,并且找不到所选文件。否则,这将是在用户界面中选择它的最佳时机。

如果你真的想解决这个问题,最好修改L& F或创建一个新的,但这对我来说听起来很多。下面的代码是一个快速而肮脏的黑客,我在查看似乎也解决问题的问题时写了,但它显然没有生产就绪,我不想将它用于任何重要的事情 - 使用你的风险自负

import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;

public class SelectedFileChooser {
    public static void main(String[] arguments) {
        SwingUtilities.invokeLater(() -> new SelectedFileChooser().createAndShowGui());
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame("Stack Overflow");
        frame.setBounds(100, 100, 800, 600);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        JButton openButton = new JButton("Test open");
        panel.add(openButton);
        frame.getContentPane().add(panel);

        openButton.addActionListener(actionEvent -> testOpen());

        frame.setVisible(true);
    }

    private void testOpen() {
        String directory = "./.idea/";
        String fileName = "compiler.xml";

        JFileChooser fc = new JFileChooser();

        FileFilter filter = new FileNameExtensionFilter("POM", "xml");
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileFilter(filter);
        fc.setCurrentDirectory(new File(directory));

        fc.setSelectedFile(new File(directory + fileName));
        System.out.println(fc.getSelectedFile().getAbsolutePath());

        createAndStartMonitorThread(fc, fileName);

        fc.showOpenDialog(null);
    }

    private void createAndStartMonitorThread(JFileChooser fc, String fileName) {
        Thread monitorThread = new Thread(){
            private int counter;

            @Override
            public void run() {
                while (counter < 20) {
                    System.out.println("Monitoring (" + counter + ")...");
                    monitorComponents(fc.getComponents(), "", fileName);
                    System.out.println("------");
                    try {
                        sleep(60);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    counter++;
                }
            }
        };

        monitorThread.start();
    }

    private void monitorComponents(Component[] components, String prefix,
                                   String fileName) {
        for (Component component : components) {
            if (component instanceof Container) {
                Container container = (Container) component;
                if (container.getComponentCount() > 0) {
                    monitorComponents(container.getComponents(), prefix + "    ",
                                      fileName);
                }
            }

            if (component instanceof JList || component instanceof JTable) {
                System.out.println(prefix + "[" + component.getClass().getName()
                                   + "] " + component);

                if (component instanceof JList) {
                    selectInList((JList) component, fileName);
                } else {
                    selectInTable((JTable) component, fileName);
                }
            }
        }
    }

    private void selectInList(JList list, String fileName) {
        int rowIndexToSelect = -1;
        System.out.println("list size: " + list.getModel().getSize());
        for (int rowIndex = 0; rowIndex < list.getModel().getSize(); rowIndex++) {
            Object value = list.getModel().getElementAt(rowIndex);
            System.out.println("Value at [" + rowIndex + ", 0] == " + value);
            if (value.toString().endsWith(fileName)) {
                rowIndexToSelect = rowIndex;
            }
        }

        System.out.println("Before change - list selection: "
                           + list.getSelectionModel().getMinSelectionIndex() + ".."
                           + list.getSelectionModel().getMaxSelectionIndex());

        if (rowIndexToSelect != -1) {
            list.getSelectionModel().setSelectionInterval(rowIndexToSelect,
                                                          rowIndexToSelect);

            System.out.println("After change - list selection: "
                               + list.getSelectionModel().getMinSelectionIndex() + ".."
                               + list.getSelectionModel().getMaxSelectionIndex());
        }

        System.out.println();
    }

    private void selectInTable(JTable table, String fileName) {
        int rowIndexToSelect = -1;
        System.out.println("table row count: " + table.getModel().getRowCount());
        for (int rowIndex = 0; rowIndex < table.getModel().getRowCount(); rowIndex++) {
            Object value = table.getModel().getValueAt(rowIndex, 0);
            System.out.println("Value at [" + rowIndex + ", 0] == " + value);
            if (value.toString().endsWith(fileName)) {
                rowIndexToSelect = rowIndex;
            }
        }

        System.out.println("Before change - table selection: "
                           + table.getSelectionModel().getMinSelectionIndex() + ".."
                           + table.getSelectionModel().getMaxSelectionIndex());

        if (rowIndexToSelect != -1) {
            table.getSelectionModel().setSelectionInterval(rowIndexToSelect,
                                                           rowIndexToSelect);

            System.out.println("After change - table selection: "
                               + table.getSelectionModel().getMinSelectionIndex() + ".."
                               + table.getSelectionModel().getMaxSelectionIndex());
        }

        System.out.println();
    }
}