gpt4 book ai didi

java - 如何使用 JFileChooser 加载文件?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:44:55 26 4
gpt4 key购买 nike

在 Java 中,我想使用 JFileChooser 以自己的格式加载文件 [无论它是什么格式]。意味着我不想读取和显示我的 JFrame 中的内容。相反,我希望它们像在 Windows Photo Viewer/Irfan Viewer 中打开图像和在 Adob​​e 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
}
}
});

示例代码来自 site :

关于java - 如何使用 JFileChooser 加载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27288636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com