Answer the question
In order to leave comments, you need to log in
Where to specify the initial path of the file selection dialog?
Hi, there is a file selection dialog code, but when you run it, it launches the Documents folder. How can I change the initial file selection path to the folder that I need?
public class FileChooser extends JFrame {
public FileChooser() {
super("Select File");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(Box.createVerticalGlue());
final JLabel label = new JLabel("The selected file");
label.setAlignmentX(CENTER_ALIGNMENT);
panel.add(label);
panel.add(Box.createRigidArea(new Dimension(10, 10)));
JButton button = new JButton("Select the file");
button.setAlignmentX(CENTER_ALIGNMENT);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
label.setText(file.getName());
}
}
});
panel.add(button);
panel.add(Box.createVerticalGlue());
getContentPane().add(panel);
setPreferredSize(new Dimension(260, 220));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void fileCh() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
new FileChooser();
}
});
}
}
Answer the question
In order to leave comments, you need to log in
So let's start reading the Javadoc! :)
docs.oracle.com/javase/7/docs/api/javax/swing/JFil...
We look at the constructors
and voila! We find, for example, the following options:
JFileChooser()
Constructs a JFileChooser pointing to the user's default directory.
JFileChooser(File currentDirectory)
Constructs a JFileChooser using the given File as the path.
The default (JFileChooser()) constructor opens starting from the default folder (In your case, this is the HOME directory)
But the second one, with the ability to specify the start directory, is what you need.
Or you can later call the setCurrentDirectory(File dir);
Everything is written in the description.
PS: This question does not apply to the "Swift" tag :) and not to "JavaFX" either. This is Swing
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question