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());
}
}
}
Related
I've been trying to use JFileChooser but I have the problem that the program doesn't stop running, here's my code:
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class copiarArcivos {
public static void main(String[] args) {
JFileChooser();
}
public static void JFileChooser(){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(new JFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}
}
}
Should I simply put a break at the end of the if?
Don't create an empty JFrame. You can just use null:
//int result = fileChooser.showOpenDialog(new JFrame());
int result = fileChooser.showOpenDialog(null);
You have to change the method name of JFileChooser in main method. and also in the declaration of this method. You can use JFileChooser2 instid of JFileChooser on both.
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!
I want my jfilechooser to display without blocking parent but i tried everything and still it is blocking parent. Any Solution....
public class main_class {
public static void main(String[] args) {
JFrame parent_frame = new JFrame("PARENT");
if (parent_frame != null) {
parent_frame.setBounds(50, 50, 500, 500);
parent_frame.setVisible(true);
parent_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog(null, "Ok");
}
}
}
By default, showDialog will use a modal dialog.
JFileChooser is simply based on a JComponent, so, so long as you don't mind that your code won't block, you could add the JFileChooser to a frame/dialog that you can yourself.
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"));
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);