Disabling New Folder Button in File chooser not working properly - java

I disable the new Folder button using the following code:
public void disableNewFolderButton( Container c ) {
System.out.print("in disable fn");
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton)comp;
Icon icon = b.getIcon();
if (icon != null
&& icon == UIManager.getIcon("FileChooser.newFolderIcon"))
{
System.out.print("in disable fn");
b.setEnabled(false);
}
}
else if (comp instanceof Container) {
disableNewFolderButton((Container)comp);
}
}
}
The code is called in the following lines:
JFileChooser of=new JFileChooser();
of.setAcceptAllFileFilterUsed(false);
of.addChoosableFileFilter(new MyFilter());
disableNewFolderButton(of);
But the new folder button is disabled only when the file chooser is first displayed. Suppose i go to some drive , say g: , then the button is enabled again. How to set this right?

this is working for me...
//Create a file chooser
UIManager.put("FileChooser.readOnly", Boolean.TRUE);
JFileChooser fc = new JFileChooser();

Disable the "new folder" Action (which in turn will disable the button):
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class FileChooserAction
{
public static void createAndShowUI()
{
JFileChooser chooser = new JFileChooser();
BasicFileChooserUI ui = (BasicFileChooserUI)chooser.getUI();
Action folder = ui.getNewFolderAction();
folder.setEnabled(false);
chooser.showSaveDialog(null);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

1) It is a bit stupid, but you can keep disabling it in an another Thread. Until the file chooser got invisible.
2) Does hiding the button work? b.setVisible(false);

Related

Window showing in last place rather than first place

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());
}
}
}

"Open file..." dialog box won't close

Hi, I am new to the Java language. I used Eclipse as my development tool. I have code to open the file dialog box and it did, but I have two problems:
When I select the file and click the "Open" button in the dialog box, the dialog box appears again instead of closing.
Sometimes the text in filename textbox in the dialog is unclear and/or the text on the button disappears. If I enlarge the dialog, the text will show completely.
Here is my code:
package PDFAnnotationPackage;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import java.io.*;
public class MainForm extends JFrame implements ActionListener {
public static void main(String[] args) {
// TODO Auto-generated method stub
new MainForm();
}
public MainForm(){
super("Example");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setSize(300, 300);
setLocation(200, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(MainForm.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
System.out.println("Open menu item clicked");
// load from file
}
if (fileChooser.showOpenDialog(this) == JFileChooser.CANCEL_OPTION ) {
}
} else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
}
How can I solve the issues? Thanks in advance.
Your dialog box appear again because you're calling a method showOpenDialog twice. Try this
if (command.equals("Quit")) {
// Close application
} else if (command.equals("Open")) {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(parent);
if (returnVal == FileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
} else if (command.equals("Save")) {
// Save menu item action
}
You're calling fileChooser.showOpenDialog(this) multiple times and that's why your program is behaving as it's behaving. Instead call fileChooser.showOpenDialog(this) once, and save its value to a variable.
In fact, you don't even need this empty block:
if (fileChooser.showOpenDialog(this) ==
JFileChooser.CANCEL_OPTION ) {
}
So get rid of it!

Cannot hide SystemTray JPopupMenu when it loses focus

This question is similar to this one. What I have is a JPopupMenu that pops up from an icon on the system tray. At this point, the system tray is the only manifestation of the program. That is, there are no other windows open, the icon in the system tray is the only way I can access the program. I used a JPopupMenu over the AWT PopupMenu because I wanted to get the system Look and Feel applied to the popup menu - when I used just a plain PopupMenu, I could not get the system's Look and Feel, I just kept getting Swing's Metal Look and Feel. I used this work-around to get this behavior (described here):
systemTrayPopupMenu = buildSystemTrayJPopupMenu();
trayIcon = new TrayIcon(iconImage, "Application Name", null /* Popup Menu */);
trayIcon.addMouseListener (new MouseAdapter () {
#Override
public void mouseReleased (MouseEvent me) {
if (me.isPopupTrigger()) {
systemTrayPopupMenu.setLocation(me.getX(), me.getY());
systemTrayPopupMenu.setInvoker(systemTrayPopupMenu);
systemTrayPopupMenu.setVisible(true);
}
}
};
When I right click on the tray icon, it shows the menu, and naturally, when I make a selection, the menu disappears. However, when I bring up the menu, then click out of it, it does not disappear. To make it disappear currently, I have to either make a selection, or select one of the menu items that are disabled.
I tried adding a FocusListener to it, however, there is no indication that the focusLost or focusGained methods ever get called. Additionally, I cannot make it disappear when another Window gains focus because there are no other windows present. Since this pop-up menu comes from a TrayIcon and not a typical button, I cannot use the solution mentioned here to get around the FocusListener not calling focusLost.
Ultimately, what I am wondering is either:
1) Is there a way to get the system's look and feel for a normal AWT PopupMenu?, or
2) Is there a way to make the JPopupMenu disappear when it loses focus?
EDIT: Per request, here is my SSCCE:
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SwingSystemTray {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run () {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new SwingSystemTray ();
} catch (Exception e) {
System.out.println("Not using the System UI defeats the purpose...");
e.printStackTrace();
}
}
});
}
protected SystemTray systemTray;
protected TrayIcon trayIcon;
protected JPopupMenu systemTrayPopupMenu;
protected Image iconImage;
public SwingSystemTray () throws IOException {
iconImage = getIcon ();
if (SystemTray.isSupported()) {
systemTray = SystemTray.getSystemTray();
systemTrayPopupMenu = buildSystemTrayJPopupMenu();
trayIcon = new TrayIcon(iconImage, "Application Name", null /* Popup Menu */);
trayIcon.addMouseListener (new MouseAdapter () {
#Override
public void mouseReleased (MouseEvent me) {
if (me.isPopupTrigger()) {
systemTrayPopupMenu.setLocation(me.getX(), me.getY());
systemTrayPopupMenu.setInvoker(systemTrayPopupMenu);
systemTrayPopupMenu.setVisible(true);
}
}
});
try {
systemTray.add(trayIcon);
} catch (AWTException e) {
System.out.println("Could not place item at tray. Exiting.");
}
}
}
protected JPopupMenu buildSystemTrayJPopupMenu () {
final JPopupMenu menu = new JPopupMenu ();
final JMenuItem showMenuItem = new JMenuItem("Show");
final JMenuItem hideMenuItem = new JMenuItem("Hide");
final JMenuItem exitMenuItem = new JMenuItem("Exit");
hideMenuItem.setEnabled(false);
ActionListener listener = new ActionListener () {
#Override
public void actionPerformed (ActionEvent ae) {
Object source = ae.getSource();
if (source == showMenuItem) {
System.out.println("Shown");
showMenuItem.setEnabled(false);
hideMenuItem.setEnabled(true);
}
else if (source == hideMenuItem) {
System.out.println("Hidden");
hideMenuItem.setEnabled(false);
showMenuItem.setEnabled(true);
}
else if (source == exitMenuItem) {
System.exit(0);
}
}
};
for (JMenuItem item : new JMenuItem [] {showMenuItem, hideMenuItem, exitMenuItem}) {
if (item == exitMenuItem) menu.addSeparator();
menu.add(item);
item.addActionListener(listener);
}
return menu;
}
protected Image getIcon () throws IOException {
// Build the 16x16 image programmatically, start with BMP Header
byte [] iconData = new byte[822];
System.arraycopy(new byte [] {0x42,0x4d,0x36,0x03, 0,0,0,0, 0,0,0x36,0,
0,0,0x28,0, 0,0,16,0, 0,0,16,0, 0,0,16,0, 24,0,0,0, 0,0,0,3},
0, iconData, 0, 36);
for (int i = 36; i < 822; iconData[i++] = 0);
for (int i = 56; i < 822; i += 3) iconData[i] = -1;
return ImageIO.read(new java.io.ByteArrayInputStream(iconData));
}
}
I found a hack that I feel will work just nicely. I have yet to test it in Windows XP, but it works in Windows 7. This involves adding a "hidden dialog" that displays behind the popup menu, as if the popup menu originated from the hidden dialog in the first place. The only real trick is getting the hidden dialog to stay behind the popup menu. At least in Windows 7, it displays behind the system tray, so you never really see it in the first place. A WindowFocusListener can be added to this hidden dialog, and so when you click out of the popup menu, you are also clicking out of the hidden dialog. I have added this capability to the SSCCE that I posted previously to illustrate how adding this works:
package org.test;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SwingSystemTray {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run () {
try {
/* We are going for the Windows Look and Feel here */
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new SwingSystemTray ();
} catch (Exception e) {
System.out.println("Not using the System UI defeats the purpose...");
e.printStackTrace();
}
}
});
}
protected SystemTray systemTray;
protected TrayIcon trayIcon;
protected JPopupMenu systemTrayPopupMenu;
protected Image iconImage;
/* Added a "hidden dialog" */
protected JDialog hiddenDialog;
public SwingSystemTray () throws IOException {
iconImage = getIcon ();
if (SystemTray.isSupported()) {
systemTray = SystemTray.getSystemTray();
systemTrayPopupMenu = buildSystemTrayJPopupMenu();
trayIcon = new TrayIcon(iconImage, "Application Name", null /* Popup Menu */);
trayIcon.addMouseListener (new MouseAdapter () {
#Override
public void mouseReleased (MouseEvent me) {
if (me.isPopupTrigger()) {
systemTrayPopupMenu.setLocation(me.getX(), me.getY());
/* Place the hidden dialog at the same location */
hiddenDialog.setLocation(me.getX(), me.getY());
/* Now the popup menu's invoker is the hidden dialog */
systemTrayPopupMenu.setInvoker(hiddenDialog);
hiddenDialog.setVisible(true);
systemTrayPopupMenu.setVisible(true);
}
}
});
trayIcon.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent ae) {
System.out.println("actionPerformed");
}
});
try {
systemTray.add(trayIcon);
} catch (AWTException e) {
System.out.println("Could not place item at tray. Exiting.");
}
}
/* Initialize the hidden dialog as a headless, titleless dialog window */
hiddenDialog = new JDialog ();
hiddenDialog.setSize(10, 10);
/* Add the window focus listener to the hidden dialog */
hiddenDialog.addWindowFocusListener(new WindowFocusListener () {
#Override
public void windowLostFocus (WindowEvent we ) {
hiddenDialog.setVisible(false);
}
#Override
public void windowGainedFocus (WindowEvent we) {}
});
}
protected JPopupMenu buildSystemTrayJPopupMenu () {
final JPopupMenu menu = new JPopupMenu ();
final JMenuItem showMenuItem = new JMenuItem("Show");
final JMenuItem hideMenuItem = new JMenuItem("Hide");
final JMenuItem exitMenuItem = new JMenuItem("Exit");
hideMenuItem.setEnabled(false);
ActionListener listener = new ActionListener () {
#Override
public void actionPerformed (ActionEvent ae) {
/* We want to make sure the hidden dialog goes away after selection */
hiddenDialog.setVisible(false);
Object source = ae.getSource();
if (source == showMenuItem) {
System.out.println("Shown");
showMenuItem.setEnabled(false);
hideMenuItem.setEnabled(true);
}
else if (source == hideMenuItem) {
System.out.println("Hidden");
hideMenuItem.setEnabled(false);
showMenuItem.setEnabled(true);
}
else if (source == exitMenuItem) {
System.exit(0);
}
}
};
for (JMenuItem item : new JMenuItem [] {showMenuItem, hideMenuItem, exitMenuItem}) {
if (item == exitMenuItem) menu.addSeparator();
menu.add(item);
item.addActionListener(listener);
}
return menu;
}
protected Image getIcon () throws IOException {
// Build the 16x16 image programmatically, start with BMP Header
byte [] iconData = new byte[822];
System.arraycopy(new byte [] {0x42,0x4d,0x36,0x03, 0,0,0,0, 0,0,0x36,0,
0,0,0x28,0, 0,0,16,0, 0,0,16,0, 0,0,16,0, 24,0,0,0, 0,0,0,3},
0, iconData, 0, 36);
for (int i = 36; i < 822; iconData[i++] = 0);
for (int i = 56; i < 822; i += 3) iconData[i] = -1;
return ImageIO.read(new java.io.ByteArrayInputStream(iconData));
}
}
This solution gives me requirement #2 that I was looking for, which is to make the JPopupMenu disappear when it loses focus on a system tray using the Windows system look and feel.
Note: I have not gotten the JPopupMenu feature to work on the system tray in CentOS/RedHat Linux. For those, I will have to just use a normal AWT PopupMenu.
A JPopupMenu can't be displayed by itself. That is it needs to be added to a window. Try to use a WindowListener and then hide the popup on a windowDeactivated() event. After the popup is visible you should be able to get the window by using:
Window window = SwingUtilities.windowForComonent(systemTrayPopupMenu);
I just used a MouseListener on the JPopup menu which invokes a timer Thread upon mouse exit; if the mouse re-enters, I reset the "mouseStillOnMenu" flag. Set the "Thread.sleep() value to however long you want the user to be able leave the menu - if you click on a a menu item normally, the default menu close behavior is invoked and closes the menu.
#Override
public void mouseEntered(MouseEvent arg0) {
mouseStillOnMenu = true;
}
#Override
public void mouseExited(MouseEvent arg0) {
mouseStillOnMenu = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000); //waits one second before checking if mouse is still on the menu
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!isMouseStillOnMenu()) {
jpopup.setVisible(false);
}
}
}).start();
}

How to delete a file through JFileChooser?

How could i delete a file in JFileChooser? I know that the AWT since being written in native could has an option to delete a file from it using the simple Delete button.
But what if i would like to delete the file in JFileChooser? When i am trying to delete, it i got an exception that the File is being accessed by another program and hence could not be deleted.
Two questions that i would like to ask in this situation are..
Questions
Is there any hack to delete a file through JFileChooser?
Why i am not getting File is being accessed by another program when i am deleting in FileDialog. Is it because it is written in native code?
Any help is appreciated. Thanks in advance.
Yeah! I got it! I even updated the JFileChooser after the file was deleted.
Updated
Added functionality to delete multiple files and modified jf.getUI().rescanCurrentDirectory(jf) to jf.rescanCurrentDirectory() and removed superfluous PropertyChangeListener as per sir Rob Camick's suggestion.
/*
* #see http://stackoverflow.com/a/17622050/2534090
* #author Gowtham Gutha
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
class DeleteThroughJFileChooser extends JFrame
{
JButton jb;
JFileChooser jf;
File[] selectedFiles;
public DeleteThroughJFileChooser()
{
// Create and show GUI
createAndShowGUI();
}
private void createAndShowGUI()
{
// Set frame properties
setTitle("Delete through JFileChooser");
setLayout(new FlowLayout());
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create JFileChooser
jf=new JFileChooser();
// Allow multiple selection
jf.setMultiSelectionEnabled(true);
// Create JButton
jb=new JButton("Open JFileChooser");
// Add ActionListener to it
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
// Show the file chooser
showFileChooser();
}
});
// Register the delete action
registerDelAction();
// Add JButton jb to JFrame
add(jb);
}
private void showFileChooser()
{
// Show the open dialog
int op=jf.showOpenDialog(this);
}
private void registerDelAction()
{
// Create AbstractAction
// It is an implementation of javax.swing.Action
AbstractAction a=new AbstractAction(){
// Write the handler
public void actionPerformed(ActionEvent ae)
{
JFileChooser jf=(JFileChooser)ae.getSource();
try
{
// Get the selected files
selectedFiles=jf.getSelectedFiles();
// If some file is selected
if(selectedFiles!=null)
{
// If user confirms to delete
if(askConfirm()==JOptionPane.YES_OPTION)
{
// Call Files.delete(), if any problem occurs
// the exception can be printed, it can be
// analysed
for(File f:selectedFiles)
java.nio.file.Files.delete(f.toPath());
// Rescan the directory after deletion
jf.rescanCurrentDirectory();
}
}
}catch(Exception e){
System.out.println(e);
}
}
};
// Get action map and map, "delAction" with a
jf.getActionMap().put("delAction",a);
// Get input map when jf is in focused window and put a keystroke DELETE
// associate the key stroke (DELETE) (here) with "delAction"
jf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"),"delAction");
}
public int askConfirm()
{
// Ask the user whether he/she wants to confirm deleting
// Return the option chosen by the user either YES/NO
return JOptionPane.showConfirmDialog(this,"Are you sure want to delete this file?","Confirm",JOptionPane.YES_NO_OPTION);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new DeleteThroughJFileChooser();
}
});
}
}
Why would you delete a file from the chooser?
Use the jfilechooser to get the name of the file and location store as a variable. Close the file jfilechooser. Then delete the file.
import java.io.File;
public class DeleteFileExample
{
public static void main(String[] args)
{
try{
File file = new File("c:\\logfile20100131.log");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Also, I found this code that might prove to be usefull if you want the functionality to be in the jfilechooser itself. From Here. To run this you will also need This. Swing file
import darrylbu.util.SwingUtils;
import java.awt.Container;
import java.awt.Point;
import java.awt.event.*;
import javax.swing.*;
public class FileChooserDeleteMenu {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FileChooserDeleteMenu().makeUI();
}
});
}
public void makeUI() {
final JFileChooser chooser = new JFileChooser();
final JList list = SwingUtils.getDescendantOfType(JList.class, chooser, "Enabled", true);
JPopupMenu popup = list.getComponentPopupMenu();
JMenuItem item = new JMenuItem("Delete");
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (chooser.getSelectedFile() != null) {
JOptionPane.showConfirmDialog(chooser,
"Delete " + chooser.getSelectedFile().getAbsolutePath() + "?",
"Confirm delete",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
}
}
});
popup.add(item);
final MouseListener listener = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if (e.getSource() == list) {
list.setSelectedIndex(list.locationToIndex(p));
} else {
JTable table = (JTable) e.getSource();
if (table.columnAtPoint(p) == 0) {
int row = table.rowAtPoint(p);
table.getSelectionModel().setSelectionInterval(row, row);
}
}
}
};
list.addMouseListener(listener);
final Container filePane = SwingUtilities.getAncestorOfClass(sun.swing.FilePane.class, list);
filePane.addContainerListener(new ContainerAdapter() {
#Override
public void componentAdded(ContainerEvent e) {
JTable table = SwingUtils.getDescendantOfType(JTable.class, chooser, "Enabled", true);
if (table != null) {
for (MouseListener l : table.getMouseListeners()) {
if (l == listener) {
return;
}
}
table.addMouseListener(listener);
}
}
});
chooser.showOpenDialog(null);
System.exit(0);
}
}
This is how to add a delete key listener to your JFileChooser:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.nio.file.Files;
public class JFileChooserUtilities
{
public static void registerDeleteAction(JFileChooser fileChooser)
{
AbstractAction abstractAction = new AbstractAction()
{
public void actionPerformed(ActionEvent actionEvent)
{
JFileChooser jFileChooser = (JFileChooser) actionEvent.getSource();
try
{
File selectedFile = jFileChooser.getSelectedFile();
if (selectedFile != null)
{
int selectedAnswer = JOptionPane.showConfirmDialog(null, "Are you sure want to permanently delete this file?", "Confirm", JOptionPane.YES_NO_OPTION);
if (selectedAnswer == JOptionPane.YES_OPTION)
{
Files.delete(selectedFile.toPath());
jFileChooser.rescanCurrentDirectory();
}
}
} catch (Exception exception)
{
exception.printStackTrace();
}
}
};
fileChooser.getActionMap().put("delAction", abstractAction);
fileChooser.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DELETE"), "delAction");
}
}
Code adapted from JavaTechnical's answer.

How to make JFileChooser Default to Computer View instead of My Documents

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"));

Categories