How to get properties of a selected file from a JFileChooser - java

I have an FXML controller class with a textfield that I want populated with various file properties of a file a user selects via a FileChooser.
The controller looks like:
#FXML
TextField documentName;
File file;
public void attachNewDocFileChooser() {
file = new MyFileChooser().chooser();
if (file != null) {
documentName.setText(file.getName());
} else {
documentName.setText("No file selected");
}
}
The FileChooser is created in a different class MyFileChooser:
#FXML
public File chooser() {
File file = null;
final JFileChooser fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileDialog.getSelectedFile();
}
return file;
}
I can't get the textfield documentName populated with the name of the file selected.
I'll be very grateful for any help at making this work. Thank you all in advance.
Update:
I get a java.lang.NullPointerException.
I also forgot to mention that chooser() is linked to a Label so that onMouseClicked="#chooser".

The only NullPointerException could be for documentName still being null. That is, that the #FXML did not work. Check the line number of the exception to see whether that is the case. And then go looking into the .fxml file you loaded.
#FXML(name="documentName")
public TextField documentName;

Related

Save a file and overwrite it when it exists in Java GUI

I have a button in a toolbar which has to save what I am drawing in a JFrame in Java. It works but it currently acts as a 'Save As' button. I am trying to make it overwrite the file once it is saved without showing a dialog. Can someone help me fix it?
My code:
JFileChooser fileChooser2;
this.fileChooser2 = new JFileChooser();
fileChooser2.addChoosableFileFilter(new TxtFilter2());
EDIT
public class TxtFilter2 extends FileFilter
{
public boolean accept(java.io.File file)
{
if (file.isDirectory())
return true;
return (file.getName().endsWith("xml"));
}
public String getDescription()
{
return "Save (*.xml)";
}
}
This is the button itself with the action:
if (ev.getActionCommand()=="Save2")
{
fileChooser2.setDialogType(JFileChooser.SAVE_DIALOG);
fileChooser2.setDialogTitle("Save as XML file format");
res=this.fileChooser2.showSaveDialog(this);
if (res==JFileChooser.APPROVE_OPTION)
{
this.net.saveToFile(fileChooser2.getSelectedFile().getPath()+".xml");
}
}
You could store the file or at least the path to the file in a member variable once the user saves for the first time. This would allow you to recognize whether the drawing has already been saved and allow you to overwrite it.
First you need a field to store the file/path:
private File savedFile;
then you can use it to overwrite it:
if (ev.getActionCommand().equals("Save2")) {
//Check if the drawing has already been saved, if not open the dialog
if(this.savedFile == null) {
fileChooser2.setDialogType(JFileChooser.SAVE_DIALOG);
fileChooser2.setDialogTitle("Save as XML savedFile format");
int res = this.fileChooser2.showSaveDialog(this);
if (res == JFileChooser.APPROVE_OPTION) {
final File selectedFile = fileChooser2.getSelectedFile();
//Store the selected file in the member variable
this.savedFile = selectedFile;
this.net.saveToFile(selectedFile.getPath() + ".xml");
}
}else {
//Use the previously selected file and don't show the dialog
this.net.saveToFile(this.savedFile.getPath() + ".xml");
}
}
I'm not sure if that's what you want to do and I don't know what exactly your this.net.saveToFile() method does but I hope this helps

JFileChooser Add different file types in filter

I have a JFileChooser and i want to have different options available in the type which will change the extension. The options i want are
.txt
.html
.xml
Right now I have:
JFileChooser chooser = new WritableFileChooser(Model.getSingleton().getOptionsParam().getUserDirectory());
chooser.setFileFilter(new FileFilter()
{
#Override
public boolean accept(File file)
{
if (file.isDirectory())
{
return true;
}
else if (file.isFile())
{
String lcFileName = file.getName().toLowerCase(Locale.ROOT);
return (lcFileName.endsWith(TXT_FILE_EXTENSION) || lcFileName.endsWith(HTML_FILE_EXTENSION) || lcFileName.endsWith(XML_FILE_EXTENSION) }
return false;
}
#Override
public String getDescription()
{
return Constant.messages.getString("file.format.html");
}
But only All files and HTML are available in the file type filter. Ideally, i also want to get rid of the All files options.
Also i have two different format .html's that are to be generated, is there any indicator i can add so that the file chooser is smart enough to know which one i want?
As #AndrewMcCoist said, the Oracle Tutorial on Filters is somewhat helpful but i got my answer and solution from this example.
chooser .addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));
chooser .addChoosableFileFilter(new FileNameExtensionFilter("MS Office Documents", "docx", "xlsx", "pptx"));
chooser .addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));

Why my file type isn't showing properly? [duplicate]

This question already has answers here:
JFileChooser.showSaveDialog: All files greyed out
(3 answers)
Closed 7 years ago.
I have been reading several posts in stack overflow regarding to the topic of saving and opening files.
But, I couldn't yet solve it.
And my problem is that one :
Is it normal that my panel doesn't highlight a certain type file properly (without the gray light which means that it isn't considered)
Example:
.asm should be darker than the others files in this example.
I have been testing several tests and none have been worked yet.
public Mips() throws IOException {
JFileChooser fc = new JFileChooser();
//fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//fc.showOpenDialog(fc);
//FileNameExtensionFilter filter = new FileNameExtensionFilter(".asm",".asm",".asm");
//fc.setFileFilter(filter);
fc.setFileFilter(new FileFilter() {
#Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
final String name = f.getName();
return name.endsWith(".asm");
}
#Override
public String getDescription() {
return "*.asm";
}
});
//fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.showSaveDialog(fc);
File f = fc.getSelectedFile();
//String newfile = f + "/mips.asm";
String newfile = f+".asm";
System.out.println(newfile);
try {
}catch (Exception e){
}
}
You are using a save dialog!!!
fc.showSaveDialog(fc);
There you can choose just folders and specify the filename to save (that is the reason why all files appear in grey). For opening files, use
JFileChooser.showOpenDialog

How to make a button that, when clicked, opens the %appdata% directory?

I have made a button, but I don't now how to make it open a specific directory like %appdata% when the button is clicked on.
Here is the code ->
//---- button4 ----
button4.setText("Texture Packs");
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser=new JFileChooser("%appdata%");
int status = fileChooser.showOpenDialog(this);
fileChooser.setMultiSelectionEnabled(false);
if(status == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// do something on the selected file.
}
}
And I want to make something like this ->
private void button4MouseClicked(MouseEvent e) throws IOException {
open folder %appdata%
// Open the folder in the file explorer not in Java.
// When I click on the button, the folder is viewed with the file explorer on the screen
}
import java.awt.Desktop;
import java.io.File;
public class OpenAppData {
public static void main(String[] args) throws Exception {
// Horribly platform specific.
String appData = System.getenv("APPDATA");
File appDataDir = new File(appData);
// Get a sub-directory named 'texture'
File textureDir = new File(appDataDir, "texture");
Desktop.getDesktop().open(textureDir);
}
}
Execute a command using Runtime.exec(..). However, not every OS has the same file explorer, so you need to handle the OS.
Windows: Explorer /select, file
Mac: open -R file
Linux: xdg-open file
I wrote a FileExplorer class for the purpose of revealing files in the native file explorer, but you'll need to edit it to detect operating system.
http://textu.be/6
NOTE: This is if you wish to reveal individual files. To reveal directories, Desktop#open(File) is far simpler, as posted by Andrew Thompson.
If you are using Windows Vista and higher, System.getenv("APPDATA"); will return you C:\Users\(username}\AppData\Roaming, so you should go one time up, and use this path for filechooser,
Just a simple modified Andrew's example,
String appData = System.getenv("APPDATA");
File appDataDir = new File(appData); // TODO: this path should be changed!
JFileChooser fileChooser = new JFileChooser(appData);
fileChooser.showOpenDialog(new JFrame());
More about windows xp, and windows vista/7/8

How do I restrict JFileChooser to a directory?

I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory.
How should I go about doing that?
Incase anyone else needs this in the future:
class DirectoryRestrictedFileSystemView extends FileSystemView
{
private final File[] rootDirectories;
DirectoryRestrictedFileSystemView(File rootDirectory)
{
this.rootDirectories = new File[] {rootDirectory};
}
DirectoryRestrictedFileSystemView(File[] rootDirectories)
{
this.rootDirectories = rootDirectories;
}
#Override
public File createNewFolder(File containingDir) throws IOException
{
throw new UnsupportedOperationException("Unable to create directory");
}
#Override
public File[] getRoots()
{
return rootDirectories;
}
#Override
public boolean isRoot(File file)
{
for (File root : rootDirectories) {
if (root.equals(file)) {
return true;
}
}
return false;
}
}
You'll obviously need to make a better "createNewFolder" method, but this does restrict the user to one of more directories.
And use it like this:
FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("X:\\"));
JFileChooser fileChooser = new JFileChooser(fsv);
or like this:
FileSystemView fsv = new DirectoryRestrictedFileSystemView( new File[] {
new File("X:\\"),
new File("Y:\\")
});
JFileChooser fileChooser = new JFileChooser(fsv);
You can probably do this by setting your own FileSystemView.
The solution of Allain is almost complete. Three problems are open to solve:
Clicking the "Home"-Button kicks the user out of restrictions
DirectoryRestrictedFileSystemView is not accessible outside the package
Starting point is not Root
Append #Override to DirectoryRestrictedFileSystemView
public TFile getHomeDirectory()
{
return rootDirectories[0];
}
set class and constructor public
Change JFileChooser fileChooser = new JFileChooser(fsv); into JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
I use it for restricting users to stay in a zip-file via TrueZips TFileChooser and with slight modifications to the above code, this works perfectly. Thanks a lot.
No need to be that complicated. You can easily set selection mode of a JFileChooser like this
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
You can read more reference here How to Use File Choosers

Categories