繁体   English   中英

如何使用JFileChooser加载文件?

[英]How to load a File using JFileChooser?

在Java中,我想使用JFileChooser以自己的格式加载文件[无论格式如何]。 意味着我不想阅读和显示JFrame的内容。 相反,我希望它们像在Windows照片查看器/ Irfan Viewer中打开的图像一样打开/加载,并在Adobe Reader中打开PDF通过单击按钮。

我搜索了很多。 但是我阅读的所有教程都告诉我们如何通过单击JButton来打印“打开此文件/您选择此文件”这一行。 实际上没有人在点击按钮上打开/加载文件。 可能是因为我是Java新手,所以我说的不正确。 我希望我的问题很清楚,请帮助......

这是我从教程页面获得的代码:

 public class JFileChooserTest {

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("JComboBox Test");
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton button = new JButton("Select File");
        button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showOpenDialog(null);
            if (returnValue == JFileChooser.APPROVE_OPTION) {
              File selectedFile = fileChooser.getSelectedFile();
              System.out.println(selectedFile.getName());
            }
          }
        });
        frame.add(button);
        frame.pack();
        frame.setVisible(true);
    }    
}

这是我想用Java做的事情。 这是windows的一个例子:

浏览按钮单击打开此窗口

当我选择XLS文件并单击“打开”按钮时,将打开一个XLS文件。 我想用Java做同样的事情。 希望现在更清楚了。

您可以尝试使用Desktop.open()

Desktop.getDesktop().open(selectedFile);

编辑你需要在这里更新:

button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent ae) {
      JFileChooser fileChooser = new JFileChooser();
      int returnValue = fileChooser.showOpenDialog(null);
      if (returnValue == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        java.awt.Desktop.getDesktop().open(selectedFile);//<-- here
      }
   }
});

网站示例代码:

如果我理解正确,您需要选择一个文件并将其传递给系统的默认应用程序。 不幸的是,这在您的操作系统上非常可靠。 对于Windows,您可以将其传递给命令行,如下所示:

        String systemcall = "cmd /C start \"\" \"" + absolutePath + "\"";
        Runtime runTime = Runtime.getRuntime();
        HomeLogger.instance().info("EXECUTE " + systemcall);
        runTime.exec(systemcall);

String绝对路径必须是文件的确切位置,例如“C:\\ test.txt”。 我希望有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM