Simple JFileChooser FileFilter not working - java

The following is a simple code for saving a file on a user input directory using a JFileChooser derived from this as suggested by this answer from another stackoverflow question. However, this code will not work as intended as the file filter does not display all the defined filters.
public static void main(String[] args) {
JFrame main = new JFrame();
JButton saveto = new JButton("save");
saveto.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser();
int retval = chooser.showDialog(chooser, "Save");
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
if (retval == JFileChooser.APPROVE_OPTION)
{
File f_sample = chooser.getSelectedFile();
System.out.println(f_sample + ".csv");
}
}
});
main.add(saveto);
main.setSize(300,300);
main.setLocationRelativeTo(null);
main.setVisible(true);
main.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
The file f_sample also will contain null but removing the filter will cause the file f_sample to work as intended, containing the file selected. So I assumed that the cause of the malfunction is on the FileFilter
What is wrong with the file filter? And how can I make it work? Note that the code is from the Oracle Tutorial with a small modification.
Last minute modification
So I used chooser.addChoosableFileFilter(filter); instead of chooser.setFileFilter(filter); and the file f_sample now contains the file defined by the user. However, the defined filters will still not show on the JFileChooser window.

You are showing your chooser before setting the filter
change to
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images",
"jpg", "gif");
chooser.setFileFilter(filter);
int retval = chooser.showDialog(chooser, "Save");
// etc

Related

Java Swing: how to make setFileFilter() work beyond the directory the FileChooser is set to

I have a function openFileAction() that is called when I click the 'File' > 'Open' option in my JMenuBar. Its first lines look like this:
private static String myPath = ... // some path
private void openFileAction() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(myPath));
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File f = null;
try {
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setFileFilter(new FileNameExtensionFilter(null, ".txt");
f = fileChooser.getSelectedFile();
...
I only want to see .txt files as suggestions -- so I call setFileFilter() on my fileChooser.
This works fine for the directory fileChooser is set to, myPath -- i.e., in the 'Open' pop-up window that appears, I see only .txt files (and folders) in that directory. However, if I navigate away from myPath in the pop-up window, let's say to Desktop, I see all files (and folders) there, and no longer only the .txt files, as I would like to.
How can I see only .txt files in any directory I navigate to?
First, configure the dialog the way you want it, before you show it, so, instead of...
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(myPath));
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File f = null;
try {
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setFileFilter(new FileNameExtensionFilter(null, ".txt");
f = fileChooser.getSelectedFile();
You should be doing something more like...
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(myPath));
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setFileFilter(new FileNameExtensionFilter(null, ".txt");
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File f = null;
try {
f = fileChooser.getSelectedFile();
Second, configure the FileFilter correctly. You should be giving it some kind of "description", as this get's presented to the user and you don't need the . in the extension, instead, it should be more like...
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt");
Runnable example...
import java.awt.EventQueue;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
File myPath = new File(".");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(myPath);
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt"));
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("You have selected " + selectedFile);
}
}
});
}
}
I'd also consider taking a closer look at How to Use File Choosers

JFileChooser confusion

I have to write a program that essentially makes a report card, but it cannot do so until until it reads in a file either through command line arguments or by the user picking one from their browser, which means I need to use JFileChooser. I have the GUI set-up for the JFileChooser but that's all I can figure out. The dialog window opens when I click open but after picking a file the window I created (GUI) does not close. Also the program runs through all of my other methods before a file is even loaded causing other problems. I tried using a do-while loop but it just runs through the loop before I can ever open a file.
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MP1 extends JFrame implements java.awt.event.ActionListener{
static StudentAssignments geen165 = new StudentAssignments();
static boolean fileReady = false;
/**
* #param args the command line arguments
*/
public static void main(String [] args) {
do{
if(args.length == 0 || args[0].isEmpty()){//reads in input from file
//select
MP1 doIt = new MP1();
doIt.setVisible(true);
}
else{
geen165.readGradeFile(args[0]);//reads in input file from command
//argument
}
}while(!fileReady);
//test methods
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
geen165.addAssignments(3, 98, 100);
geen165.saveGradeFile("NewGrades.txt");
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
geen165.removeAssignment(0, 2);
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
}
//JFile Chooser GUI
public MP1(){
prepareGui();
}
private void prepareGui(){
setSize(500,500);
Container window = getContentPane();
window.setLayout(new FlowLayout());
JButton open = new JButton("Open");
JButton cancel = new JButton("Cancel");
JLabel status = new JLabel("You've selected: ");
//sets file when open is pressed
open.addActionListener((ActionEvent e) -> {
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(window);
if(returnVal == JFileChooser.APPROVE_OPTION){
File fileName = chooser.getSelectedFile();
status.setText("You've selected: " + fileName.getName());
geen165.readGradeFile(fileName.getName());
fileReady=true;
}
});
//exits program if cancel is pressed
cancel.addActionListener((ActionEvent e) -> {
System.exit(1);
});
window.add(open);
window.add(cancel);
window.add(status);
setDefaultCloseOperation(HIDE_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change
//body of generated methods, choose Tools | Templates.
}
}
Any suggestions?
You are complicating a simple issue. There is no need for you to build a window and everything only to use JFileChooser. A simple solution that works is
import javax.swing.*;
public class MP1 extends JFrame {
public static void main(String[] args) {
String myFile="";
if (args.length == 0 || args[0].isEmpty()) {//reads in input from file
//select
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
if (returnVal!=JOptionPane.CANCEL_OPTION) {
myFile = chooser.getSelectedFile().getPath();
} else {
JOptionPane.showMessageDialog(null, "Thanks for playing!");
System.exit(0);
}
} else {
myFile = args[0];
}
JOptionPane.showMessageDialog(null, "You have selected "+myFile+". Go play!");
}
}
Notice that I check whether there is a parameter. If not, I immediately go and execute the JFileChooser. There is no need for overhead.
I removed all your class activity, because I do not have the files.
BTW, I have not tested it, but I believe that your problem comes from your new frame not being modal. Hence, the boolean variable is changed before you can do anything. But that is just an idea.
I think you need to know how JFileChooser works.
JFileChooser fc = new JFileChooser();
int optionSelected = fc.showOpenDialog(YourClassName.this);
if (optionSelected == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
... // Do what you want with the file
}
JFileChooser

Can't interact with JFileChooser window, not clickable or closeble

In my code I am asking the user to choose an image. My JFileChooser window worked fine. Then I restarted my computer and now whenever that window comes up it is not clickable in any way. I can't open a file, I can't cancel, I can't chooser folders or files. Here is the necessary code.
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "jpeg");
jfc.setFileFilter(filter);
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setVisible(true);
int ret = jfc.showOpenDialog(null);
if (ret == JFileChooser.CANCEL_OPTION) {
return;
}
File file_1 = jfc.getSelectedFile();
file_path = file_1.getAbsolutePath();
Breakpoints show that the program never leaves this line:
int ret = jfc.showOpenDialog(null);
As I said the same exact code was working fine moments ago. Not sure what is causing this situation.
In my main program I click "Add image" which calls the previously mentioned code. I try clicking on the window "Open" opened by "showOpenDialog" but it doesn't matter where I click. Nothing changes. The main program resumes once I close the "Open" window from my task manager. Also in my task manager "Open" window doesn't say not responding, it looks fine and closes at an instance and furthermore inside the text field the text cursor is blinking.
EDIT: Same exact code works on a separate project that consists of only this code.
EDIT 2: Some additional codes.
Here is the complete load_file() function.
public class Image {
private static String file_path;
private static ImageFrame frame;
public static boolean isImgLoaded = false;
public static void load_file(){
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "jpeg");
jfc.setFileFilter(filter);
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setVisible(true);
int ret = jfc.showOpenDialog(null);
if (ret == JFileChooser.CANCEL_OPTION) {
return;
}
File file_1 = jfc.getSelectedFile();
file_path = file_1.getAbsolutePath();
ImageFrame frm = new ImageFrame();
frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frm.setVisible(true);
frame = frm;
isImgLoaded = frame.get_component().is_img_loaded();
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
closeFrame();
}
});
}
Here is the button code that calls the function when pressed. shlErgo is my shell that the UI is built on.
Button btnAddImage = new Button(shlErgo, SWT.NONE);
btnAddImage.setBounds(230, 10, 75, 25);
btnAddImage.setText("Add Image");
btnAddImage.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
if (!Image.isImgLoaded){
Image.load_file();
}
else{
Error.translate(2);
}
}
});

how to insert a picture using file chooser

I'm creating a program to register employees, and was wondering how to put a picture of the employees registered When do your record. I would use a button to select this file and attach the photo along with your registration? But how would this be done using JavaFX? Thank you!!
I managed as follows:
#FXML
private void searchPicture(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
File file = fileChooser.showOpenDialog(new Stage());
if (file != null) {
Image img = new Image(file.toURI().toString());
imagem.setImage(img);
imagem.setFitWidth(171);
imagem.setFitHeight(176);
imagem.setPreserveRatio(false);
}
}
}

Java: JFileChooser How to show Selected File in a textField

I have a JFileChooser and Im able to print the Absolute Path in console.
I need to show the FilePath in a Text field as soon as the User selects the file.
Below is the code please let me know how to do it.
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int showOpenDialog = fileChooser.showOpenDialog(frame);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) return;
Please let me know if you need any other details.
You need to listen to the changes that occur when using the JFileChooser, see this snipet of code:
JFileChooser chooser = new JFileChooser();
// Add listener on chooser to detect changes to selected file
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser)evt.getSource();
File oldFile = (File)evt.getOldValue();
File newFile = (File)evt.getNewValue();
// The selected file should always be the same as newFile
File curFile = chooser.getSelectedFile();
} else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(
evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser)evt.getSource();
File[] oldFiles = (File[])evt.getOldValue();
File[] newFiles = (File[])evt.getNewValue();
// Get list of selected files
// The selected files should always be the same as newFiles
File[] files = chooser.getSelectedFiles();
}
}
}) ;
All you need to do inside the first condition is set the value of your textfield to match the new selected filename. See this example:
yourTextfield.setText(chooser.getSelectedFile().getName());
Or just
yourTextfield.setText(curFile.getName());
It is the method getName() from class File that will give you what you need.
Help your self from de API docs to see what each method does.
You can use this code to show the path in a text field.
if(fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
using what Genhis has said, please see the full code block you can use to get a 'browse' button to place the file path in a correlating JTextField.
JButton btnNewButton = new JButton("Browse");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("C:/Users"));
fc.setDialogTitle("File Browser.");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (fc.showOpenDialog(btnNewButton) == JFileChooser.APPROVE_OPTION){
textField.setText(fc.getSelectedFile().getAbsolutePath());
}
}
});

Categories

Resources