getAbsolutePath() NullPointerException - java

I'm working on a Halo: CE custom game launcher in Java, and I'm setting up a preferences system using the Properties class in Java, so the user can set custom game paths. I use a JFileChooser to select a file and then write that path to the config file.
But, the program gives a Null Pointer Exception at this line: (This is in the event listener function)
if(source == fovChooseButton)
{
int returnVal = chooseFile.showOpenDialog(settingsWindow);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File selected = chooseFOV.getSelectedFile();
try
{
config.setProperty("STLPath", selected.getAbsolutePath()); //This line gives the exception
config.store(new FileOutputStream(CONFIG_FILE), null);
}
catch(Exception e)
{
handleException(e);
}
}
}
I do have another JFileChooser, and it does not throw any exceptions. Here's the code for the other one:
if(source == fileChooseButton)
{
int returnVal = chooseFile.showOpenDialog(settingsWindow);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File selected = chooseFile.getSelectedFile();
try
{
config.setProperty("GamePath", selected.getAbsolutePath());
config.store(new FileOutputStream(CONFIG_FILE), null);
}
catch(Exception e)
{
handleException(e);
}
} // end if
}
All handleException() does is display a dialog window with the stack trace.
Help?

Your prompting the User for a file with chooseFile afterwards you are trying to read the file from the other filechooser chooseFOV
int returnVal = chooseFile.showOpenDialog(settingsWindow);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File selected = chooseFOV.getSelectedFile();

What's chooseFOV ? You seem to be using chooseFile for the dialog, so it's the one that's got a selection.

int returnVal = chooseFile.showOpenDialog(settingsWindow);
File selected = chooseFOV.getSelectedFile();
You have two variables and probably want to use chooseFile on the second line as well.

Related

How to avoid .getSelectedFile() premature selection?

It appears that the .getSelectedFile() functions will still choose a folder from a file chooser even after choosing the cancel option. Is there a different function? Like getOpenedFolder(), maybe? I would appreciate any help. Here is my code:
boolean flag = false;
fc.setCurrentDirectory(new java.io.File("C:/Users/michaelartichoke/Desktop"));
fc.setDialogTitle("PDF Manager");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(null);
chosenfolder = fc.getSelectedFile();
try{
folderpath = chosenfolder.getAbsolutePath();
flag = true;
} catch(Exception e){
//
}
if(flag!=false){
selecting();
}
FYI, selecting() is the command that creates the database.
You need to look at the result that showOpenDialog() returned to see if the user chose "Open":
int res = fc.showOpenDialog(null);
if (res==JFileChooser.APPROVE_OPTION) {
// User picked 'Open"
chosenfolder = fc.getSelectedFile();
// ...
}

Cannot select folders as directories using JFileChooser

I am currently trying to use JFileChooser to return the path of a file or directory as a string. However, I found that I cannot choose a folder as my selection until I choose a file first. While this isn't a major issue it is by far frustrating to solve.
Gfycat of what is happening: https://gfycat.com/DeadlyDeliriousAzurevase
Code:
public static String openFileChooser()
{
int returnValue = fileChoose.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
fileChoose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
return (fileChoose.getSelectedFile().getAbsoluteFile().toString());
}
else
{
return "null";
}
}
Help would be absolutely appreciated, thank you!
You're setting the file selection mode after you've shown the dialog and the user has clicked the button. It won't have any effect at that point. You need to set it before you show the file chooser dialog.
The line you need to move up to be the first line in your method is:
fileChoose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
You should change your code to
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(fileChooser.getSelectedFile().getAbsoluteFile().toString());
} else {
System.out.println("Empty");
}
make sure invoke
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
before you open your dialog

Having trouble with JFileChooser if/else statement

I'm trying to allow the user to either select an already created .ser file and save over it, or create a new .ser file by typing in a new name in the JFileChooser textfield. As you can see from the code below, I used a if/else statement to determine which of the two the user is doing. The problem I'm experiencing is that no matter how I rearrange things, or use different if conditions, the JFileChooser always chooses the latter option (create a new .ser file by typing in a new name). This wouldn't be a big problem, but it always adds ".ser" to the file.
For example: If I create a new file in JFC called mySERObject, it will be saved as "mySERObject.ser." Now when I open JFC again, and I select with my mouse mySERObject.ser, to save over, it instead creates a new file called "mySERObject.ser.ser."
I uses the System.out.println to see which statement gets exected, and it's always the "First one printed." Here's my code:
private void addSaveAsListener(JMenuItem item) {
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Serialized Object Files", "ser", ".ser");
fc.setFileFilter(filter);
final JTextField textField = getTextField(fc); //gets text from JFC textfield
int returnVal = fc.showSaveDialog(null);
String fileName = textField.getText();
if (returnVal == JFileChooser.APPROVE_OPTION) {
if (!(fc.getSelectedFile().length() > 0)) {
System.out.println("first one printed");
File file = new File(fc.getCurrentDirectory(), fileName
+ ".ser");
try {
file.createNewFile();
fileSystem.saveAs(addressbook.getCopyList(), file.getAbsolutePath()); //serializes arraylist
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File unable to be created.");
}
} else {
String path = fc.getSelectedFile().getAbsolutePath();
fileSystem.saveAs(addressbook.getCopyList(), path); //serializes arraylist
System.out.println("2nd one printed");
}
}
}
});
}
I was wondering if you could help me with what's wrong or by offering solutions, thank you.
Question 1: There is always another suffix added, what can I do?
Look at the following code from your example. You will see, that you get the textfield from the fc, then get the string from that (aka "mySERObject.ser") and then you gone save again, with ".ser" appendig. You can maybe use some String opperations on fileName to get rid of the suffix before further processing (for example with fileName.replace(".ser", "")).
final JTextField textField = getTextField(fc);
String fileName = textField.getText();
//fileName.replace(".ser", "")
File file = new File(fc.getCurrentDirectory(), fileName + ".ser");
Question 2: In my if/else block only if clause will be selected. Why?
I personally don't know much about JFileChooser, but fc.getSelectedFile().length() seems not to work like you think, since it always returns 0. But you can just use fileName.length(), can't you?

How to deny choose same file with JFileChooser

I am creating program whose function is that reading "n" .txt or .java files and of these files creates a UML diagram. I have reading method, but I came to problem with load more same files. I would like to deny load same files, because it makes problems with creating a UML diagram.
I trying to solve it so that I store uploaded file into ArrayList and checking each load file with files saved in ArrayList, where are previous loaded files.
Next problem is that I click to button Yes or No when I choose same file, file is equally loaded.
And when I creating this answer I found next problem. When user select more then one file, ArrayList don't know how to add two files at once.
Is there anyone option how I would solve this problem more easily?
ArrayList<String> filenames = new ArrayList<String>();
JTabbedPane tabbedPaneUML_Files = new JTabbedPane();
private void readFiles() {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
FileNameExtensionFilter fileFilter =
new FileNameExtensionFilter("Only .txt a .java files",
"txt", "java");
fc.setFileFilter(fileFilter);
int returnValue = fc.showOpenDialog(this);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File[] files = fc.getSelectedFiles();
File file;
tabbedPaneUML_Files.addTab("UML diagram", panelUML);
for (int i = 0; i < files.length; i++) {
file = files[i];
for (int j = 0; j < filenames.size(); j++) {
if (filenames.get(i).equals(fc.getSelectedFile().getName())) {
Object[] options = {"Yes", "No"};
int answer = JOptionPane.showOptionDialog(this,
"Unable to load the same files! To retrieve the other files?",
"Load new file", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if(answer == 0) {
readFiles();
}
}
}
filenames.add(file.getName());
JTextArea loadCode = new JTextArea();
JScrollPane scrollingFile = new JScrollPane();
scrollingFile.setViewportView(loadCode);
tabbedPaneUML_Files.addTab("" + file.getName(), scrollingFile);
int ch;
try {
Reader charsReader =
new InputStreamReader(new FileInputStream(file),
"UTF-8");
while ((ch = charsReader.read()) != -1) {
loadCode.append(Character.toString((char) ch));
}
loadCode.setSelectionStart(0);
loadCode.setSelectionEnd(0);
loadCode.setEditable(false);
} catch (FileNotFoundException ex) {
Logger.getLogger(HlavniOkno.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HlavniOkno.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Thanks for any advice. I already lost ideas.
Sorry for my English.
You can use the validatedFileChooser found here
and tweak it so instead of having a list of invalid filenames, have a list of the already chosen files.
Then you can just edit this part:
if (file.exists() && getDialogType() == SAVE_DIALOG) {
int confirm = JOptionPane.showConfirmDialog( this, file.getName() + " already exists! Would you like to overwrite it?", "File already exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE );
if (confirm != JOptionPane.YES_OPTION)
return;
}
to say getDialogType() == LOAD_DIALOG and the error message to: "file has already been loaded" for example.
As for the multiple filenames, do File[] files = chooser.getSelectedFiles(); to get the list of files chosen, iterate through them to get their names and then store them in the array for already selected filenames.
edit - sorry just saw you have already done File[] files = chooser.getSelectedFiles();, so all you need to do is add it to the array containing the already loaded filenames.

JFileChooser, want to lock it to one directory

I have this program where u can download files and i want the JFileChooser to be locked to one folder(directory) so that the user cant browse anything else. He can only choose files from for example the folder, "C:\Users\Thomas\Dropbox\Prosjekt RMI\SERVER\". I have tried so search but did not find anything.
The code I have is:
String getProperty = System.getProperty("user.home");
JFileChooser chooser = new JFileChooser(getProperty + "/Dropbox/Prosjekt RMI/SERVER/"); //opens in the directory "//C:/Users/Thomas/Dropbox/Project RMI/SERVER/"
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
And this is working fine, but now i can go to the folder Project RMI, that i don't want it to do.
Thanks in Advance :)
Edit: What I did with your help:
JFileChooser chooser = new JFileChooser(getProperty + "/Dropbox/Project RMI/SERVER/");
chooser.setFileView(new FileView() {
#Override
public Boolean isTraversable(File f) {
return (f.isDirectory() && f.getName().equals("SERVER"));
}
});
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: "
+ chooser.getSelectedFile().getName());
}
Set a FileView and override the isTraversable method so that it returns true only for the directory you want the user to see.
Here is an example:
String getProperty = System.getProperty("user.home");
final File dirToLock = new File(getProperty + "/Dropbox/Prosjekt RMI/SERVER/");
JFileChooser fc = new JFileChooser(dirToLock);
fc.setFileView(new FileView() {
#Override
public Boolean isTraversable(File f) {
return dirToLock.equals(f);
}
});
Make a custom FileSystemView, use it as the argument to one of the JFileChooser constructors that accepts an FSV..
In my case I needed to disable both directory navigation and choosing a different file extension Here's another approach for posterity: a small recursive method to disable the navigation controls:
private void disableNav(Container c) {
for (Component x : c.getComponents())
if (x instanceof JComboBox)
((JComboBox)x).setEnabled(false);
else if (x instanceof JButton) {
String text = ((JButton)x).getText();
if (text == null || text.isEmpty())
((JButton)x).setEnabled(false);
}
else if (x instanceof Container)
disableNav((Container)x);
}
Then call as follows:
JFileChooser fc = new JFileChooser(imgDir);
disableNav(fc);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif", "png");
fc.setFileFilter(filter);
...

Categories

Resources