So I have created a Java GUI application, I have a main form, and I run this class PathBrowser by clicking a jbutton, The JFileChooser runs twice though, I have tried adding the opendialog from my mainform so I can have the same logo on the window.
Here's my code:
public class PathBrowser {
public static String filepath = null;
public static void main(String[] args)
{
JButton select = new JButton();
JFileChooser browse = new JFileChooser();
//add the icon of main form for JFileChooser
//OPENS TWICE?! Error
browse.showOpenDialog(MainForm.frame);
//if blank goes to user/documents. Unsure about other OSes
browse.setCurrentDirectory(new java.io.File("C:/"));
browse.setDialogTitle("Browse Folder");
browse.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//when clicked open (approve option)
if (browse.showOpenDialog(select) == JFileChooser.APPROVE_OPTION){
//folder has peen selected
MainForm.selfolder = true;
//add the path to the string filepath
filepath = (browse.getSelectedFile().getAbsolutePath());
System.out.println("The path for the server is: "+browse.getSelectedFile().getAbsolutePath());
//add the information to the textarea
MainForm.textArea.setText("The path for the server is: "+browse.getSelectedFile().getAbsolutePath());
}
}
}
Thanks
You are calling browse.showOpenDialog twice, that's why you get it twice.
Just remove this line :
browse.showOpenDialog(MainForm.frame);
And to keep the frame's icon, replace
browse.showOpenDialog(select)
with
browse.showOpenDialog(MainForm.frame)
Related
When I use JFileChooser, it opens the dialog window in the last place, not in the first place.
It is not showing as the first window = it doesn't "pop up" after I run the program.
It works, when I use it in the main, but when I use it in method, it is doing this.
import javax.swing.JDialog;
import javax.swing.JFileChooser;
public class JFrameChooser {
public static void vyberSuboru() {
JFileChooser fileChooser = new JFileChooser();
JDialog dialog = new JDialog();
int result = fileChooser.showOpenDialog(dialog);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println(fileChooser.getSelectedFile().getAbsolutePath());
}
}
}
You are creating the file chooser with a newly created dialog which is empty and not visible. Instead use your applications's main window as parent.
Something this way:
public class JFrameChooser {
public static void vyberSuboru(JDialog parent) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(parent);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println(fileChooser.getSelectedFile().getAbsolutePath());
}
}
}
I am dealing with this swing component JfileChooser . I am selecting multiple file and then clicked ok .
After that if i again open to select the file it is showing me the previous selected file which i dont want .
I want previous directory to be maintained but not the previous files .It gives very Bad User experience .
Here is the code Snippet what i have written.
JFileChooser fileopen = new JFileChooser();
private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileButtonActionPerformed
fileopen.setMultiSelectionEnabled(true);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File[] file = fileopen.getSelectedFiles();
fileText.setText(file[0].getAbsolutePath());
for( int i =1;i < file.length;i++)
{
fileText.append("||");
fileText.append(file[i].getAbsolutePath());
}
}else {
log.info("File access cancelled by user.");
}
}//GEN-LAST:event_fileButtonActionPerformed
I tried with those setcurrentdirecotory and all . Any help will be appreciated.
Either create a new instance of JFileChooser each time you need it or call setSelectedFiles and pass it null
Updated
So, I had a quick look at the setSelectedFile and setSelectedFiles methods and they should be clearing the selection and the "file name" field, but it doesn't seem to be working for me on Mac OS, so it's likely a look and feel issue.
What I tend to do is cheat. I store the last directory value in the Preferences API, I do this because it's super easy and it also means that the value persists across executions, super helpful. If you don't want to persist it across executions, you could use a Map or Properties or some other variable, that's up to you
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("...");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileopen = new JFileChooser();
String path = Preferences.userNodeForPackage(TestPane.class).get("FileAccess.lastSelectedDirectory", null);
if (path != null) {
File filePath = new File(path);
if (filePath.exists() && filePath.isDirectory()) {
fileopen.setCurrentDirectory(filePath);
}
}
fileopen.setMultiSelectionEnabled(true);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File[] file = fileopen.getSelectedFiles();
System.out.println("You selected " + file.length + " files");
Preferences.userNodeForPackage(TestPane.class).put("FileAccess.lastSelectedDirectory", fileopen.getCurrentDirectory().getAbsolutePath());
} else {
System.out.println("File access cancelled by user.");
}
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
I'm trying to get the JFileChooser to remember the location of the previous location opened, and then next time open there, but is doesn't seem to remember. I have to open it twice:
At the first run it works fine. But at the second run there's still the path locked from the first run. I have to open the JFileChooser dialog twice to get the newer path...
//Integrate ActionListener as anonymous class
this.openItem.addActionListener(new java.awt.event.ActionListener() {
//Initialise actionPerformed
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
//Generate choose file
this.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = this.chooser.showOpenDialog(PDFcheck.this.openItem);
if (this.theOutString != null){
this.chooser.setCurrentDirectory(new File(this.theOutString)); }
if(returnVal == JFileChooser.APPROVE_OPTION) {
//theOutString = fc.getSelectedFile().getName();
this.theOutString = this.chooser.getSelectedFile().getPath();
System.out.println("You chose to open this file: " + this.theOutString);}
}
private String theOutString;
private final JFileChooser chooser = new JFileChooser();
});
thanks ;-)
Problem is that you first show the file chooser dialog, and you only set its current directory after that.
You should first set the current directory first and then show the dialog:
if (this.theOutString != null)
this.chooser.setCurrentDirectory(new File(this.theOutString));
int returnVal = this.chooser.showOpenDialog(PDFcheck.this.openItem);
In the Windows Look and Feel for JFileChooser, the left hand side of the JFileChooser dialog shows five buttons: Recent Items, Desktop, My Documents, Computer, and Network. These each represent Views of the file system as Windows Explorer would show them. It appears that JFileChooser defaults to the My Documents View unless the setSelectedFile() or setCurrentDirectory() methods are called.
I am attempting to make it easy for the user to select one of a number of mapped network drives, which should appear in the "Computer" View. Is there a way to set the JFileChooser to open the "Computer" view by default?
I have tried a couple methods to force it, the most recent being to find the root directory and set it as the currentDirectory, but this shows the contents of that root node. The most recent code is included below.
private File originalServerRoot;
private class SelectOriginalUnitServerDriveListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser origDriveChooser = new JFileChooser();
origDriveChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File startFile = new File(System.getProperty("user.dir")); //Get the current directory
// Find System Root
while (!FileSystemView.getFileSystemView().isFileSystemRoot(startFile))
{
startFile = startFile.getParentFile();
}
origDriveChooser.setCurrentDirectory(startFile);
origDriveChooser.setDialogTitle("Select the Mapped Network Drive");
int origDriveChooserRetVal = origDriveChooser.showDialog(contentPane,"Open");
if (origDriveChooserRetVal == JFileChooser.APPROVE_OPTION)
{
originalUnitServerRoot = origDriveChooser.getSelectedFile();
}
}
}
Is there a method that allows me to select the "Computer" view by default (or the Network, or any other view), or any way to trick the JFileChooser?
EDIT
Thanks for the quick and thorough answers. I combined Hovercraft Full Of Eels' and Guillaume Polet's answers to try and make the code work on any drive letter. The resulting code is as follows. Once again, thanks.
private File originalServerRoot;
private class SelectOriginalUnitServerDriveListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser origDriveChooser = new JFileChooser();
origDriveChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File startFile = new File(System.getProperty("user.dir")); //Get the current directory
// Find System Root
while (!FileSystemView.getFileSystemView().isFileSystemRoot(startFile))
{
startFile = startFile.getParentFile();
}
//Changed the next line
origDriveChooser.setCurrentDirectory(origDriveChooser.getFileSystemView().getParentDirectory(rootFile));
origDriveChooser.setDialogTitle("Select the Mapped Network Drive");
int origDriveChooserRetVal = origDriveChooser.showDialog(contentPane,"Open");
if (origDriveChooserRetVal == JFileChooser.APPROVE_OPTION)
{
originalUnitServerRoot = origDriveChooser.getSelectedFile();
}
}
}
Here is a working example. It makes the assumption that C:\ is a valid path. It uses the FileSystemView.getParentDir(File)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().initUI();
}
});
}
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
final JButton button = new JButton("Select files...");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(
chooser.getFileSystemView().getParentDirectory(
new File("C:\\")));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showDialog(button, "Select file");
}
});
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
A kludge way to do this is to get the default directory's parent until the toString() of the File obtained is "Computer". something like:
FileSystemView fsv = FileSystemView.getFileSystemView();
File defaultFile = fsv.getDefaultDirectory();
while (defaultFile != null) {
defaultFile = defaultFile.getParentFile();
if (defaultFile != null && "Computer".equalsIgnoreCase(defaultFile.toString())) {
JFileChooser fileChooser = new JFileChooser(defaultFile);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
System.out.println(file);
}
}
}
//Specify the absolute path of the Mapped Drive
chooser.setCurrentDirectory(new File("B:\\exampleFolder"));
OR
// set the file opener to look at the desktop
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(System.getProperty("user.home") + "\\Desktop"));
When I double click a directory JFileChooser is not opening that directory i.e. it's not browsing it but it selects the directory and returns.
How can I implement JFileChooser so that it will show the folder's content when I double click?
If setFileSelectionMode(JFileChooser.FILES_ONLY) is set then the behaviour is good as my needs but I have to use FILES_AND_DIRECTORIES.
you can add your own MouseListener
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(arg0.getClickCount() == 2) {
File file = fileChooser.getSelectedFile();
if(file.isDirectory()) {
fileChooser.setCurrentDirectory(file);
fileChooser.rescanCurrentDirectory();
}
else {
fileChooser.approveSelection();
}
}
}
//Other methods (can be empty)
});
This checks for double clicks and gets the selected file from the JFileChooser checks if that's a directory and if it is follows it, if it's a file it returns the file. Also if you select a directory and hit open it opens the directory.