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.
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'm beginning with GUI and listeners. I want to choose and set file from pc into the "File zvolenysubor" in class Hlavna by another class implementing ActionListener.
I can choose file in the listener's actionPerformed method and set it into "File subor" but I fail in saving it into the "File zvolenysubor" in my main (and all of my ideas how to do it failed too).
What should I change/add there please?
Here are my classes:
public class Hlavna {
public static void main(String[] args) {
File zvolenysubor = null;
JFrame frame = new JFrame("ABCDE");
JButton vybersuboru = new JButton("vyber");
vybersuboru.setBounds(220, 15, 200, 20);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.add(vybersuboru);
frame.setLayout(null);
VyberListener list1 = new VyberListener(zvolenysubor);
vybersuboru.addActionListener(list1);
vybersuboru.setText("vyber subor");
}
}
public class VyberListener implements ActionListener {
private File subor;
public VyberListener(File subor){
this.subor = subor;
}
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
System.out.println("lol");
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
chooser.showOpenDialog(null);
subor = chooser.getSelectedFile();
System.out.println(subor.getAbsolutePath());
}
}
Not really sure what you're asking here. Java passes method arguments by value as opposed to reference, so the File parameter you're supplying to the constructor of VyberListener is only updated in the VyberListener class by the actionPerformed method, not the reference in your main method. What is it you're trying to accomplish here?
If you're trying to update "File zvolenysubor" in your main method, it may be worthwhile making your "File subor" in your VyberListener class public, so that it can be accessed by the main method.
Update
To minimise the amount of chatter in the comments below, I'll try and summarise. Although Java supports pass by reference, it's actually only passing pointers by reference. Thus in your example, you pass a null object reference (subor) to your ActionListener, which is then overwritten in the actionPerformed method:
subor = chooser.getSelectedFile();
Thus your File variable "zvolenysubor" is never updated. In order to update fields in your Hlavna class, I recommend using the following "Container" pattern:
public class Hlavna {
public static void main(String[] args) {
// New "FileReference" container instance
FileReference zvolenysubor = new FileReference();
JFrame frame = new JFrame("ABCDE");
JButton vybersuboru = new JButton("vyber");
vybersuboru.setBounds(220, 15, 200, 20);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.add(vybersuboru);
frame.setLayout(null);
VyberListener list1 = new VyberListener(zvolenysubor);
vybersuboru.addActionListener(list1);
// Retrieves the updated File instance
File updatedFile = zvolenysubor.getFile();
}
}
public class VyberListener implements ActionListener {
private FileReference subor;
public VyberListener(FileReference subor){
this.subor = subor;
}
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
chooser.showOpenDialog(null);
subor.setFile(chooser.getSelectedFile());
}
}
// FileReference container class allows the file reference to be updated by the ActionListener
// without re-initialising the object reference
public class FileReference {
private File _file;
public void setFile(File file) {
_file = file;
}
public File getFile() {
return _file;
}
}
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 have a simple swing window in order to load files.
This appear in the class analyzedLoad, in a function analyzedloads()
JFileChooser fc = new JFileChooser();
JFrame frame = new JFrame();
int returnVal = fc.showOpenDialog(frame);
frame.dispose();
if (returnVal == JFileChooser.APPROVE_OPTION) {
Where I apply the function without get an input from the user, all fine. But where I get an input from the user, in this way:
int al= 0;
Scanner in = new Scanner(System.in);
System.out.println("for choose file, press 1; for save, press 2");
al= in.nextInt();
if (al== 1){
analyzedLoad.analyzedloads(); // A static function which open the swing window
The window doesn't appear, and the process continue to run, without doing anything.
Thanks.
Becaue "a scanning operation may block waiting for input," I suspect you're blocking the event dispatch thread. Instead use a File Chooser to obtain a file reference.
Try adding a second mywindow.setVisible(true) after the console operation.
You might want to try to declaring the analyzeLoad variable as final and do something like so:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
analyzedLoad.analyzedloads();
}
}
or since the method is static:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
YourClass.analyzedloads();
}
}
That being said, without more code we can only speculate.
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);