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

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

Related

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 get properties of a selected file from a JFileChooser

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;

How to display an image(all major formats), selected by JFileChooser in java

I am developing an image editing app, so want to display an image selected by JFileChooser, so what would be best approach so that it can display all formats jpg, png, gif etc. OpenButton is used for invocation of filechooser.
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChosser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChosser.getSelectedFile();
// What to do with the file
// I want code for this part
try {
//code that might create an exception
}
catch (Exception e1) {
e.printStackTrace();
}
}
}
The easiest way is probably to create an ImageIcon from the URL of the file (or from the content of the file as bytes, or from the file name), and to wrap this ImageIcon into a JLabel:
iconLabel.setIcon(new ImageIcon(file.toURI().toURL()));
But if your app is supposed to edit the image, then you'll have to learn how to manipulate java.awt.Image instances, and the easiest way won't be sufficient.

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