I'm trying make a JFileChooser for selecting a folder. In this FileChooser, I'd like users to have the option of creating a new folder, and then selecting that. I've noticed that JFileChooser "Save" dialogs have a "new folder" button by default, but no similar button appears in "open" dialogs. Does anyone know how to add a "new folder" button to an "Open" dialog?
Specificially, I'd like to add the button to a dialog created using this code:
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileFilter( new FileFilter(){
#Override
public boolean accept(File f) {
return f.isDirectory();
}
#Override
public String getDescription() {
return "Any folder";
}
});
fc.setDialogType(JFileChooser.OPEN_DIALOG);
frame.getContentPane().add(fc);
frame.pack();
frame.setVisible(true);
Ok. In the end I solved this by using a "save" dialog instead of an "open" dialog. The standard save dialog already has a "new folder" button, but it also has a "Save as:" panel at the top, which I didn't want. My solution was to use a standard save dialog, but to hide the "Save as" panel.
Here's the code for the save dialog:
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileFilter( new FileFilter(){
#Override
public boolean accept(File f) {
return f.isDirectory();
}
#Override
public String getDescription() {
return "Any folder";
}
});
fc.setDialogType(JFileChooser.SAVE_DIALOG);
fc.setApproveButtonText("Select");
frame.getContentPane().add(fc);
frame.setVisible(true);
This part locates and hides the "Save as:" panel:
ArrayList<JPanel> jpanels = new ArrayList<JPanel>();
for(Component c : fc.getComponents()){
if( c instanceof JPanel ){
jpanels.add((JPanel)c);
}
}
jpanels.get(0).getComponent(0).setVisible(false);
frame.pack();
End result:
EDIT
There's one quirk with this solution, which comes up if the user presses the approve button while there's no directory currently selected. In this case the directory returned by the chooser will correspond to whatever directory the user was viewing, concatenated with the text in the (hidden) "save as:" panel. The resulting directory may be one that doesn't exist. I handled this with the code below.
File dir = fc.getSelectedFile();
if(!dir.exists()){
dir = dir.getParentFile();
}
Related
I have the following Java 8 Swing code:
JButton button = new JButton("Browse");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose file as input");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Filter", "xls", "xlsx");
fileChooser.setFileFilter(filter);
if (fileChooser.showOpenDialog(mainWindow) == JFileChooser.APPROVE_OPTION) {
File selection = fileChooser.getSelectedFile();
createFile(selection);
}
}
});
The idea is that the user selects a directory and then types the name of a new file that the app will then create. But when I click the button this is what I see:
Notice how there's no "File Name" text field where you can enter the new file name? What configurations do I need to change in order to get this?
You're using the showOpenDialog which, as the name suggests, shows a "Open File" dialog to select a file to open. It usually doesn't make sense to allow a non-existent file to be opened.
If you want to allow the user to select a new file, you probably want the showSaveDialog which shows a "Save File" dialog and (should) allow a new file to be created.
In Java I want to load a file [whatever format it is] in its own format using JFileChooser. Means I don't want to read and display the contents inside my JFrame. Instead I want them to open/load like an image open in a Windows Photo Viewer/Irfan Viewer and a PDF open in Adobe Reader By clicking a Button.
I had searched a lot. But all tutorial I read tells how to print a line "opening this file/You are selected this file" by clicking a JButton. Nobody is actually opening/loading a file on a button click. May be I am not getting correctly what they said because I am new to Java. I hope my problem is clear and please help...
Here is the code that I got from a tutorial page:
public class JFileChooserTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComboBox Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
Here is what I want to do with Java. here is an example with windows:
A Browse Button Click opens this window
And when I select the XLS file and click OPEN button, an XLS file will open. I want to do the exact same with Java. Hope it is more clear now.
You may try using Desktop.open():
Desktop.getDesktop().open(selectedFile);
EDIT
You need to update here:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
java.awt.Desktop.getDesktop().open(selectedFile);//<-- here
}
}
});
Sample code from site:
If I understand you correctly, you want to select a file and pass it to the system's default application. Unfortunately, this is highly dependable on your operating system. For Windows you can pass that to the command line like this:
String systemcall = "cmd /C start \"\" \"" + absolutePath + "\"";
Runtime runTime = Runtime.getRuntime();
HomeLogger.instance().info("EXECUTE " + systemcall);
runTime.exec(systemcall);
The String absolute Path must be the exact locatin of the file, e.g. "C:\test.txt". I hope that helps!
When I open file that show the dialog box, I need to change Java image and add my own image. How to customize dialog box?
For example, I need to add the Encoding to the dialog box and how to add different type of files to Files of type dropdown box. For Example, i add text, java, html to Files of type box.
Here is my code,
FileDialog fd = new FileDialog(OpenExample.this, "Select File", FileDialog.LOAD);
fd.setVisible(true);
To provide an icon for a file chooser or dialog, set an icon for the parent frame.
import java.awt.image.BufferedImage;
import javax.swing.*;
public class FileChooserIcon {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
// see nice icons in chooser!
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {}
JLabel ui = new JLabel("Big Space");
ui.setBorder(new javax.swing.EmptyBorder(40, 200, 40, 200));
JFrame f = new JFrame("Show file chooser icon");
f.setIconImage(new BufferedImage(
20, 20, BufferedImage.TYPE_INT_RGB));
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(ui);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(f); // use frame icon!
}
};
SwingUtilities.invokeLater(r);
}
}
.. how to add different type of files to Files of type dropdown box? For example: add text, java, html to Files of type box.
See How to Use File Choosers: FileChooserDemo2 which offers a file filter for Just Images..
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
add(menubar,BorderLayout.NORTH);
menubar.add(file);
JMenuItem Open = new JMenuItem("OPEN... Ctrl+O");
file.add(Open);
Open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Frame f = new Frame();
FileDialog openf = new FileDialog(f, "Open");
openf.setVisible(true);
}
});
Well, I tried to use a lot many examples on the internet which makes the open button work as you can see i have already made the design but i need help in how to open a .txt file on clicking the open button in the filedialog. how am i supposed to do that?? i would really appreciate if anyone can help me out with few lines of code that actually works as i am sick of searching error generating codes from the internet.
The documentation states:
The FileDialog class displays a dialog window from which the user can
select a file.
Since it is a modal dialog, when the application calls its show method
to display the dialog, it blocks the rest of the application until the
user has chosen a file.
Therefore, instead of calling .setVisible(true) you can call .show() on the dialog, and then you can use getFile() to get the file that was chosen, or getFiles() if you are using multipleMode.
To read the file you can use:
public static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
yourComponent.setText(readFile(openf.getFile(), Charset.defaultCharset()));
(Taken from this question)
I am trying to put a JFileChooser box on my GUI but if I just do this
JFileChooser filechooser = new JFileChooser ();
then it will just show a huge file selection window on the panel (I do not want that), so I want to make a small box filechooser (with a name for example "choose file") that when I click it, a window will popup, so then I can choose the file.
Use a button to open your file chooser and use setPreferredSize() method to make the file chooser smaller in size:
JButton button = new JButton("Choose a file!");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle( "Choose a file" );
fileChooser.setVisible( true );
fileChooser.setPreferredSize( new Dimension(100, 100) );
}
});
Call
filechooser.setPreferredSize (new java.awt.Dimension (800, 800));
before calling showOpenDialog with whatever Dimension you like.
But I would suggest to either maximize the Dialog, because in the moment I like to open a File, I don't like to watch something else - find a file, and close the dialog, without much scrolling, because somebody thought it looks more nice.
If you like to prevent wasting space, you can precalculate the needed size for the window, which might be a lot of work, but could pay off, if you use the Component frequently.