How to save JFrame Contents to File - java

I'm trying to make a program that asks the user for information and then when they click save, the text boxes and labels and all are saved into a file to be able to be shared. It could be any type of file if need be. The information is in a Tabbed pane inside a JFrame. Here is my current save method.
FileFilter ft = new FileNameExtensionFilter("Text Files", "txt", "jpg","png", "jpeg");
db.addChoosableFileFilter(ft);
int returnVal = db.showSaveDialog(this);
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
java.io.File saved_file = db.getSelectedFile();
String file_name = saved_file.toString();
try {
WriteFile data = new WriteFile(file_name, false);
String allText = JFrame.toString(); //Line im having trouble with
data.writeToFile(allText);
} catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}

JFrame.toString wont give you any state that you want to save.
The right approach is to get each value from text boxes and save/reload manually into a file.
Another approach that you can try, is to serialize the whole JFrame into a file. Look at this JavaDoc for more info.

Related

How to restrict JFileChooser to only allow a specific number of files to be selected?

I'm creating a Guess Who game as an independent final project for my object-oriented university class and was running into an issue. One of the things I want my program to be able to do is let the user upload his/her own files from the computer to be used in the guess who game. Basically, the user clicks a JRadioButton and then the FileChooser box will open so he/she can navigate to the folder with the files. I realize that you can use the setMultiSelectionEnabled(true) command to make it so that you can select multiple files, but is there a way that I can restrict the selection to only 25 images (the size of my game-board)? Is there an easier way of doing this? Should I just make it so that the user can only select folders filled with images?
The reason I want the specific files is because I want to load the images into an ImageIcon array and the names of the files (before the extensions), into an array as well.
Here is the code I have so far:
private class fileSelector implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFileChooser files = new JFileChooser(); //creates a new filechooser
files.setCurrentDirectory(new File(System.getProperty("user.home"))); //starts the filechooser at the home directory
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg", "png", "gif"); //only allows files with these extensions to be used
files.addChoosableFileFilter(filter); //adds the filter
files.setMultiSelectionEnabled(true); //makes it so you can select multiple files!
files.showOpenDialog(null);
}
}
Any help would be great! Thanks!
sadly their is no way to do this cause this is ComponentUI related !
#trashgod made great examples here
also you can make an FileFilter like this
public class ImagesFilter extends FileFilter {
#Override
public boolean accept(File f) {
if (f.isDirectory()) {
File[] list = f.listFiles();
if (list.length == 25) {
boolean ret = true;
for (File file : list) {
ret = ret && isMyImageType(file);
}
return ret;
}
}
return false;
}
#Override
public String getDescription() {
//descripe it .
return "";
}
}
and then later in the JFileChooser.getIcon(File f) override it to get a special icon that suits your project with the same class like :-
private final ImagesFilter filter = new ImagesFilter();
#Override
public Icon getIcon(File f) {
if (filter.accept(f))
{
//return your icon
}
return super.getIcon(f); //To change body of generated methods, choose
}
When you want to do something when a component changes (an event takes place), use a PropertyListener. Every time a user changes his selection an event is taking place. You can add a property listener to your file chooser and check if he has selected more files than you want.
Take a look at this example (max files 2):
JFileChooser files = new JFileChooser(); // creates a new filechooser
files.setCurrentDirectory(new File(System.getProperty("user.home"))); // starts the filechooser at the home
// directory
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg", "png", "gif"); // only allows
// be used
files.addChoosableFileFilter(filter); // adds the filter
files.setMultiSelectionEnabled(true); // makes it so you can select multiple files!
files.addPropertyChangeListener(e -> {
File[] selectedFiles = files.getSelectedFiles();
if (selectedFiles.length > 2) {
File[] selectedFilesNew = new File[2];
// Select the first 2
for (int i = 0; i < selectedFilesNew.length; i++) {
selectedFilesNew[i] = selectedFiles[i];
}
files.setSelectedFiles(selectedFilesNew);
JOptionPane.showMessageDialog(files, "Only 2 selected files allowed.", "File chooser",
JOptionPane.ERROR_MESSAGE);
}
});
files.showOpenDialog(null);
Rembember though, that this is a file count restriction and not a folder count restriction.

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?

Java Swing, On button click, output to JTextArea

I have 2 classes one of which is a GUI.
My first class is called MusicSearch.java and it has this:
public static void directoryMusicLocator(File dir) {
try
{
String[] filetype = new String[] { "mp3" }; // only search mp3 files
System.out.println("Getting all .mp3 files in " + dir.getCanonicalPath() + " including those in subdirectories");
List<File> files = (List<File>) FileUtils.listFiles(dir, filetype, true);
for (File file : files)
{
System.out.println(file.getAbsolutePath()); // get the file's absolute path
}
System.out.println("\nFinished Searching.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
What this does is that it searches for Mp3 files on a directory for example C:\Music
For the GUI, well I created it using netbeans' JFrame Designer and a screenshot of this can be seen on the image below. (I can't embed images at the moment so I can only provide a link to the image.)
http://i.stack.imgur.com/7pLPL.jpg
On the JTextField next to the "Enter Location", the user enters a location for example C:\Music. When the user clicks the button "Find MP3's" the method directoryMusicLocator is called. Below is the Action Listener for the Find MP3's button:
private void findMP3ButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String fLocation = dirToSearch.getText(); // this gets the input from the textfield
File dir = new File(fLocation); // converts the location to path
MusicSearch.directoryMusicLocator(dir);
}
An example of the output can be seen below when it is ran and user entered C:\Music on the textfield:
C:\Music\Feint - Times Like These (Fracture Design Remix).mp3
C:\Music\Ficci - Climax (FREE).mp3
C:\Music\Ficci - Making Me Blue (FREE).mp3
Now what I want is the output to display on the JTextArea but I don't know how. Can someone tell me how.
Thanks
You just have to do the following changes in your directoryMusicLocator and findMP3ButtonActionPerformed methods. Instead of directly printing you just need to store the content in a StringBuilder and return that so that you can show it in the JTextArea.
public static String directoryMusicLocator(File dir) {
try
{
String[] filetype = new String[] { "mp3" }; // only search mp3 files
StringBuilder outString = new StringBuilder("Getting all .mp3 files in " + dir.getCanonicalPath() + " including those in subdirectories\n");
List<File> files = (List<File>) FileUtils.listFiles(dir, filetype, true);
for (File file : files)
{
outString.append(file.getAbsolutePath()+"\n"); // get the file's absolute path
}
outString.append("\nFinished Searching.");
return outString.toString()
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
private void findMP3ButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String fLocation = dirToSearch.getText(); // this gets the input from the textfield
File dir = new File(fLocation); // converts the location to path
String output = MusicSearch.directoryMusicLocator(dir);
// Replace <jTextArea> with your JTextArea field name
<jTextArea>.setText(output);
}
JTextArea textArea = new JTextArea(); // instantiate the JTextArea
textArea.append("text"); // append to the existing text on JTextArea
textArea.setText("text"); // set the current text with the given one
hope this helps :)
Rather than calling System.out.println, which sends the output to the standard output steam, you should send it to the text area. But you can't do that without a reference to the JTextArea that you're working with, so you need to change the signature of directoryMusicLocator to include a JTextArea like so:
public static void directoryMusicLocator(File dir, JTextArea outputTextArea) {
Then, you'll want to change System.out.println(newText) to outputTextArea.append(newText + System.getProperty("line.separator")). (Replace "newText" with the parameters that you're sending to the JTextArea.
Finally, change the call-sites for directoryMusicLocator(File) - pass a reference to the JTextArea: MusicSearch.directoryMusicLocator(dir, jTextArea1)

image save to folder in java

I am working with java. In my application i want to give facility to user to add and change image. I use open dialog box to select image, it will work properly i.e on button click open dialog is open select any image.
i want to store that selected image into specified folder (src/resources/ and that path stored into database, for furhter retrivation.
Please guide me to overcome from that problem.
Actual code:
private void btnImagenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = ElegirImagen.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = ElegirImagen.getSelectedFile();
String nombre=ElegirImagen.getSelectedFile().getName();
String sname = file.getAbsolutePath();
BufferedImage myPicture=null;
try {
myPicture = ImageIO.read(new File(sname));
} catch (IOException ex) {
Logger.getLogger(Videoteca.class.getName()).log(Level.SEVERE, null, ex);
}
lblImg.setIcon(new ImageIcon(myPicture));
lblImg.repaint();
BufferedImage i = new BufferedImage(300,500,BufferedImage.TYPE_INT_ARGB);
File fichero = new File(sname);
String formato = "jpg";
try {
ImageIO.write(i, formato, fichero);
} catch (IOException ex) {
Logger.getLogger(Videoteca.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Swing has single threading model. All generated Events are also processed by a single Queue known as EventQueue inside one single thread known as EDT(Event Dispatch Thread). Action Event is also no exception. You should not read and write file inside this thread. Rather create a new thread using the means of Anonymous class or extending Runnable and deploy your image read-write operation there.
Though it is not clear from what you are asking, but i assume that you are probably after writing an image. ImageIO has write function too to write an image file. Check out Writing/Saving an Image tutorial which contains enough description.

Modification to JFileChooser to just display folder content

i m trying to develop an gui application which display tree of filesystem on left side and on right side it display selected tree nodes (folder)'s content .
can any body tell me to do modification in jfilechooser to just to display folder content
thank you in advance
The JFileChooser#accept allows you to filter which files are displayed. A similar method is the JFileChooser#setFileFilter method
See: example
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
Perhaps this is what you expected:-
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
try {
// Create a File object containing the canonical path of the desired directory
File f = new File(new File(".").getCanonicalPath());
// Set the current directory
chooser.setCurrentDirectory(f);
} catch (IOException e1) {
e1.printStackTrace();
}
// Show the dialog; wait until dialog is closed
int returnVal = chooser.showOpenDialog(frame);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File f = chooser.getSelectedFile();
textField.setText(f.getAbsolutePath());
File[] contents = f.listFiles();
for(int file=0;file<contents.length;file++)
{
System.out.println(contents[file].getName()); //here you get the contents of the selected directory
}
}

Categories

Resources