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"));
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 am using ImageJ to build a java application which would display a dicom Image.
I was able to import the dicom image and display it successfully. But, I want to display the coronal and sagittal views of the image as well.
Is this possible using ImageJ?
The code to display the dicom image using an applet is what I have below:
// SimpleFileChooser.java
// A simple file chooser to see what it takes to make one of these work.
//
import static com.sun.org.apache.xerces.internal.util.PropertyState.is;
import ij.plugin.DICOM;
import java.applet.Applet;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class readDicom extends Applet {
public void init() {
setSize(350, 200);
JButton openButton = new JButton("Open");
final JLabel statusbar
= new JLabel("Output of your selection will go here");
// Create a file chooser that opens up as an Open dialog
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
int option = chooser.showOpenDialog(readDicom.this);
if (option == JFileChooser.APPROVE_OPTION) {
File[] sf = chooser.getSelectedFiles();
String filelist = " ";
filelist = sf[0].getName();
File file = chooser.getCurrentDirectory();
String fullpath = file.getCanonicalPath();
fullpath = fullpath + "\\" + filelist;
InputStream reader = new FileInputStream(fullpath);
DICOM dcm = new DICOM(reader);
dcm.run("Name");
dcm.show();
for (int i = 1; i < sf.length; i++) {
filelist += ", " + sf[i].getName();
}
statusbar.setText("You chose " + filelist);
} else {
statusbar.setText("You canceled.");
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
this.add(openButton);
this.add(statusbar);
}
}
The Image > Stacks > Orthogonal Views command in ImageJ can do what you need. Have a look at the source code or the javadoc if you want to use its API.
I have this code (this is all code). I want to write file path(choosing file) on JTextField. I run the program and i press button and file chooser open, i choose file but file path not write on JTextField.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.dyno.visual.swing.layouts.Bilateral;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
//VS4E -- DO NOT REMOVE THIS LINE!
public class xailabsPanel extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jButton0;
public static String path;
private JTextField jTextField0;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public xailabsPanel() {
initComponents();
}
private void initComponents() {
setLayout(new GroupLayout());
add(getJText(), new Constraints(new Bilateral(12, 12, 4), new Leading(100, 10, 10)));
add(getJButton0(), new Constraints(new Bilateral(117, 117, 94), new Leading(57, 12, 12)));
setSize(328, 252);
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("jButton0");
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
}
private JTextField getJText() {
if (jTextField0 == null) {
jTextField0 = new JTextField();
}
return jTextField0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class.
* Note: This class is only created so that you can easily preview the result at runtime.
* It is not expected to be managed by the designer.
* You can modify it as you like.
*/
private void jButton0MouseMouseClicked(MouseEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
fileChooser.setCurrentDirectory(new File(System.getProperty("home/kerim")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
// user selects a file
File selectedFile = fileChooser.getSelectedFile();
path = selectedFile.getAbsolutePath().toString();
jTextField0.setText(path);
}
}
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xailabsPanel frame = new xailabsPanel();
frame.setDefaultCloseOperation(xailabsPanel.EXIT_ON_CLOSE);
frame.setTitle("xailabsPanel");
frame.getContentPane().setPreferredSize(frame.getSize());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You are creating a new JTextField inside the method (and you are modfying its contents), but it's not added anywhere.
Drop jTextField0 = new JTextField() and it should work (assuming you already created the text field beforehand).
The code works fine, when I do the following
Change layout manager default BorderLayout (why? Because I don't have GroupLayout, it's not a standard Layout Manager - so I don't know if it's a direct cause)
Add the componenst to corresponding BorderLayout positions.
Changed setSize() to pack(). This is the preferred way.
create the text field the the constructor (new JTextField(int columns)). For some weird reason I feel like this is the culprit (as without this, the text field has no preferred size, and maybe you just weren't seeing it. Not 100% sure, hell probably not even 50% sure, as I couldn't test the GroupLayout
Got rid of frame.getContentPane().setPreferredSize(frame.getSize());, another suspected culprit (not really necessary to delete, but not preferred to keep).
Got rid of this unnecessary line, as it's redundant fileChooser.showOpenDialog(null); and causing the file chooser to open twice.
Here's the result
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
//VS4E -- DO NOT REMOVE THIS LINE!
public class xailabsPanel extends JFrame {
private static final long serialVersionUID = 1L;
private JButton jButton0;
public static String path;
private JTextField jTextField0;
private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
public xailabsPanel() {
initComponents();
}
private void initComponents() {
//setLayout(new GroupLayout());
add(getJText(), BorderLayout.WEST);
add(getJButton0(), BorderLayout.EAST);
//setSize(328, 252);
pack();
}
private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("jButton0");
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
}
private JTextField getJText() {
if (jTextField0 == null) {
jTextField0 = new JTextField(20);
}
return jTextField0;
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class. Note: This class is only created so that you can
* easily preview the result at runtime. It is not expected to be managed by
* the designer. You can modify it as you like.
*/
private void jButton0MouseMouseClicked(MouseEvent event) {
JFileChooser fileChooser = new JFileChooser();
//fileChooser.showOpenDialog(null);
//fileChooser.setCurrentDirectory(new File(System
//.getProperty("home/kerim")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
// user selects a file
File selectedFile = fileChooser.getSelectedFile();
path = selectedFile.getAbsolutePath().toString();
System.out.println(path);
jTextField0.setText(path);
}
}
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xailabsPanel frame = new xailabsPanel();
frame.setDefaultCloseOperation(xailabsPanel.EXIT_ON_CLOSE);
frame.setTitle("xailabsPanel");
//frame.getContentPane().setPreferredSize(frame.getSize());
((JPanel) frame.getContentPane()).setBorder(BorderFactory
.createEmptyBorder(20, 20, 20, 20));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You never added JTextField to your JFrame (or whatever window you want the text field to be).
Right after your JTextFIeld0 = new JTextField(); add: myWindow.add(jTextField0)
also, you are displaying two open dialogs. i dont think it is your desired behavior, remove the file fileChooser.showOpenDialog(null);
Here is a quick example of what you are trying to accomplish:
public static void main(String[] args)
{
// you should not need this, use the frame you already have, where the button is.
JFrame window = new JFrame();
// This is what you are doing in your code, however, you should add a text field
// whereever you create and populate your jframe, and add the button etc, and simply
// set the jtextfield value here
JTextField tf = new JTextField();
// again in your case you should have this somewhere else, i assume if you are
// displaying a button, you must have a JFrame somewhere
window.setSize(100, 100);
window.add(tf);
window.setLocationRelativeTo(null);
/***** you DO NEED this code **************/
// create file chooser and open the dialog.
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(null);
// get selected file object
File f = fc.getSelectedFile();
// disply file path in the text field
tf.setText(f.getAbsolutePath());
/****** end of the code you need *********/
// display a JFrame with the text field (dont need this obviously you
// already are displaying the frame)
window.setVisible(true);
}
Hi all I am creating a simple text editor as a project and I have hit a snag when it comes to saving the content typed as a file. I can save the file using the Save As principle with a dialog box prompting the user to enter a filename.
The problem I am having is implementing the Save so that it saves to the file that is opened without having to go to the dialog box each time, like it would if someone did Ctrl+S. Anyone have any ideas how I would implement this feature?
Here's some of my code:
JMenuItem saveFile = new JMenuItem(new AbstractAction("Save") {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser save = new JFileChooser();
File filename = save.getSelectedFile();
if(opened == false && saved == false) {
save.showSaveDialog(null);
int confirmationResult;
if(filename.exists()) {
confirmationResult = JOptionPane.showConfirmDialog(getParent(), "Replace existing file?");
if(confirmationResult == JOptionPane.YES_OPTION) {
saveFile(filename);
}
} else {
saveFile(filename);
}
} else {
saveFile(filename);
}
}
});
saveFile.setPreferredSize(new Dimension(100, 20));
saveFile.setEnabled(true);
save method:
private void saveFile(File filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(textArea.getText());
writer.close();
saved = true;
editorWindow.setTitle("JavaText - " + filename.getName());
} catch (IOException err) {
err.printStackTrace();
}
}
If you store the opened File object somewhere in your application you can then just pass that into your saveFile method on a key press using a KeyListener or KeyAdapter. Without seeing more of the application it's hard to tell where would be best to put it, but if you just store it in a variable somewhere you can refer back to it.
Store the file name somewhere
if(nameOfFile != null) then don't show the dialog box and go to save method
else show dialog box and call the save method
That's what I would do
The following program shows the implementation of 'Save' & 'Save as' functionality for text editors. Running it will shows a JFrame with a JTextArea , save JButton & save as JButton.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MyFrame extends JFrame {
private boolean alreadySaved = false;
private BufferedWriter bw;
private JFileChooser fileChooser;
private JTextArea jta;
private File file;
private JButton save;
private JPanel mainPanel;
private JButton saveAs;
public MyFrame() {
initComponents();
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (!alreadySaved) {
int response = fileChooser.showSaveDialog(getParent());
file = fileChooser.getSelectedFile();
if (response == JFileChooser.APPROVE_OPTION) {
writeFile();
alreadySaved = true;
}
} else
writeFile();
}
});
saveAs.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
int response = fileChooser.showSaveDialog(getParent());
file = fileChooser.getSelectedFile();
if (response == JFileChooser.APPROVE_OPTION) {
writeFile();
alreadySaved = true;
}
}
});
} // END of Constructor
public void writeFile() {
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write(jta.getText());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initComponents() {
fileChooser = new JFileChooser();
saveAs = new JButton("Save as");
jta = new JTextArea(10, 40);
mainPanel = new JPanel();
mainPanel.setBackground(Color.red);
save = new JButton("Save");
mainPanel.add(save);
mainPanel.add(saveAs);
this.setLayout(new BorderLayout());
this.add(jta);
this.add(mainPanel, BorderLayout.SOUTH);
this.pack();
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
new MyFrame().setVisible(true);
}
}