看看How to Integrate with the Desktop Class
基本上你想使用类似...
File file = new File(...);
Desktop desktop = Desktop.getDesktop();
desktop.edit(file);
或
desktop.open(file);
取决于您是否要编辑或查看文件(有时它们是相同的)
查看JavaDocs for java.awt.Desktop了解更多详情
更新了文件打开示例
根据反馈,我建议使用 JTextArea 中的 JList 来列出与 Files 匹配的内容,这样您就可以更好地控制用户实际选择和设计的内容,以及列出内容
本例需要用户双击打开文件...
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FileListExample {
public static void main(String[] args) {
new FileListExample();
}
public FileListExample() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
File[] files = new File("...").listFiles();
DefaultListModel<File> model = new DefaultListModel<>();
for (File file : files) {
model.addElement(file);
}
JList<File> list = new JList<>(model);
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
JList list = (JList) e.getComponent();
File file = (File) list.getSelectedValue();
try {
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
如果你想做一些更花哨的事情,你甚至可以提供自己的ListCellRenderer,例如...
public class FileListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Icon icon = null;
if (value instanceof File) {
File file = (File) value;
value = file.getName();
FileSystemView view = FileSystemView.getFileSystemView();
icon = view.getSystemIcon(file);
}
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setIcon(icon);
return this;
}
}
可以使用...
list.setCellRenderer(new FileListCellRenderer());