首先,我會在GUI組件中顯示多個文件路徑,以更好地顯示多個對象,如JList。另外,JFileChooser API會告訴你哪種方法只返回一個文件,並返回一個數組File[]
:getSelectedFiles()
。結束時請注意s
。
但是,當然,您不能將數組放入JTextField中,但我猜測您一旦得到數據就知道該如何處理數據。
此外,這是沒有意義的:
final JFileChooser fc = new JFileChooser();
File[] files = fc.getSelectedFiles();
既然你實際顯示的文件選擇對話框之前調用getSelectedFiles()
。你想要做的就是調用的方法你的showTxtFileFrame()
方法,就像你現在打電話getSelectedFile()
一樣。
例如:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.*;
@SuppressWarnings("serial")
public class JFileChooserExample extends JPanel {
// use a list model and JList that works *directly* with Files
private DefaultListModel<File> fileListModel = new DefaultListModel<>();
private JList<File> fileJList = new JList<>(fileListModel);
public JFileChooserExample() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(new SelectFilesAction("Select Files", KeyEvent.VK_S)));
// help set the width and height of the JList
fileJList.setVisibleRowCount(10);
fileJList.setPrototypeCellValue(new File("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
JScrollPane scrollPane = new JScrollPane(fileJList);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new BorderLayout(3, 3));
add(buttonPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
private class SelectFilesAction extends AbstractAction {
public SelectFilesAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fc.showOpenDialog(JFileChooserExample.this);
if(result == JFileChooser.APPROVE_OPTION) {
fileListModel.clear(); // clear the model of prior files
File[] files = fc.getSelectedFiles();
for (File file : files) {
// add all files to the model
fileListModel.addElement(file);
}
}
}
}
private static void createAndShowGui() {
JFileChooserExample mainPanel = new JFileChooserExample();
JFrame frame = new JFrame("JFileChooser Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
見編輯回答,請。 –