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);
}
}
});
Related
Synopsis
I am developing a Java Swing project, and I have been debugging successfully within IntelliJ IDEA by running the main method directly. After closing the frame, the debugger exits normally.
However, after adding a JFileChooser dialog to the project, the debugger does not exit normally. I have to click the stop button every time now, which causes the JVM to exit with a non-zero status.
Minimal, Reproducible Example
This is the section of code that is causing the problem; it is an ActionListener that I am adding to two buttons which launch the JFileChooser:
/**
* Generic action listener that is used for both file selection dialog buttons
*/
private final ActionListener fileSelectionButtonActionListener = new ActionListener()
{
#Override
public void actionPerformed(final ActionEvent event)
{
final String target = ((JButton) event.getSource()).getName();
assert (target.equals("file") || target.equals("directory"));
JFileChooser fileChooser = new JFileChooser(new File(".").getAbsoluteFile());
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
if(target.equals("directory")) {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
final int result = fileChooser.showOpenDialog(new JFrame());
if(result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if(target.equals("file")) {
fileTextField.setText(selectedFile.getAbsolutePath());
} else {
directoryTextField.setText(selectedFile.getAbsolutePath());
}
}
}
};
Debugging Steps
I have tried moving the JFrame creation from the parameter of the showOpenDialog method to a variable declaration and added frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); but that did not fix the issue. It's almost like the frame is still hanging around in memory, and that's why the JVM won't close.
Question
How can I make the JVM close appropriately while using JFileChooser?
The problem is, indeed, that the JFrame is still in memory, causing the JVM to hang. However, the solution is a JFrame is not needed.
Instead of setting a new JFrame() as the parent of the dialog, set the parent to the dialog window itself:
/**
* Generic action listener that is used for both file selection dialog buttons
*/
private final ActionListener fileSelectionButtonActionListener = new ActionListener()
{
#Override
public void actionPerformed(final ActionEvent event)
{
final String target = ((JButton) event.getSource()).getName();
assert (target.equals("file") || target.equals("directory"));
JFileChooser fileChooser = new JFileChooser(new File(".").getAbsoluteFile());
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
if(target.equals("directory")) {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
--> final int result = fileChooser.showOpenDialog(fileChooser); <--
if(result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if(target.equals("file")) {
fileTextField.setText(selectedFile.getAbsolutePath());
} else {
directoryTextField.setText(selectedFile.getAbsolutePath());
}
}
}
};
Change the line where you get the result: final int result = fileChooser.showOpenDialog(fileChooser);. Doing that fixes the issue.
I have game program where I want the player to choose the file directory to save his game. I am using JFileChooser for this works perfectly fine but it won't close.
here is the code:
public NewGameState(Game game) {
super(game);
open = new JButton();
fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("."));
fc.setDialogTitle("Choose file for the new world");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
public void tick() {
input();
selection();
}
public void render(Graphics g) {
drawSelection(g);
drawGUI(g);
}
private void input(){
if(game.getKeyManager().up){
selection --;
}else if(game.getKeyManager().down){
selection ++;
}
if(game.getKeyManager().space){
if(selection == 0){
fileChooser(); //calling fileChooser method when pressing space
}else if(selection == 1){
}else if(selection == 2){
}
}
}
private void selection(){
//blahbahabahaa
}
}
//fileChooser
private void fileChooser(){
fc.showOpenDialog(null);
}
I thought that space is true and it keeps executing the code every tick it turn out it won't stop reading the code which stops the ticking proccess. It keeps reading the method over and over. Other answers are using panel which I'm not using panel in this program I'm using canvas and jframe only
if this is what you are looking for just to be able to close the File Chooser Dialog after selecting the file or saving the file. Just still try to make the code more explanatory i think this should based on my understanding of what u explained
int c = fileWindow.showSaveDialog(this);
if(c==JFileChooser.APPROVE_OPTION)
files.append(fileWindow.getSelectedFile()+"\n");
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
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());
}
}
});
I'm currently trying to use FileChooserBuilder from Netbeans Platform API. Following code is complete netbeans module action. When run, it doesn't show at the center of window/screen but somewhere in bottom left corner of the screen. Is there any possibility to make this dialog display in the middle of the screen?
public final class LoadProjectAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
File home = new File(
System.getProperty("user.home")
+ File.separator + "lib");
FileChooserBuilder fileChooserBuilder = new FileChooserBuilder(
LoadProjectAction.class);
fileChooserBuilder.setTitle("Load project");
fileChooserBuilder.setDefaultWorkingDirectory(home);
fileChooserBuilder.setApproveText("Load");
fileChooserBuilder.setDirectoriesOnly(true);
File directory = fileChooserBuilder.showOpenDialog();
if (directory != null) {
return; // nothing to do
}
// do some processing here
}
}
Thanks for your ideas.
Found the solution:
You have to obtain JFileChooser instance and set right parent component in it's showOpenDialog method (it's then positioned relatively to application's main window). But as NetBeans tries to work quite safely with the threads - it allows only one thread access the components, so the EventQueue.invokeLater has to be used.
public final class LoadProjectAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
// output window
InputOutput io = IOProvider.getDefault().getIO("File search", true);
io.select();
// start in user home directory
File initialDirectory = new File(
System.getProperty("user.home")
+ File.separator + "lib");
FileChooserBuilder fileChooserBuilder = new FileChooserBuilder(
"LoadProjectAction");
fileChooserBuilder.setTitle("Load project");
fileChooserBuilder.setDefaultWorkingDirectory(initialDirectory);
fileChooserBuilder.setApproveText("Load");
fileChooserBuilder.setDirectoriesOnly(true);
JFileChooser jfc = fileChooserBuilder.createFileChooser();
int value = jfc.showOpenDialog(WindowManager.getDefault().getMainWindow());
if (value != JFileChooser.APPROVE_OPTION) {
return; // nothing to do
}
// process selection
}
});
}
}