Java Swing, On button click, output to JTextArea - java

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)

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.

How to save JFrame Contents to File

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.

How to allow a user to enter Windows Environment Variables in a JFileChooser dialog

I am using JFileChooser for my Java GUI to allow the user to browse for files to import. I am using TestComplete to create some tests for my program, and need the ability to use environment variables in the JFileChooser window "File Name:" text field.
For example, I want to be able to type the following line into the "File Name:" text box...
%TEST_FILES%\file_set_1\testfile.xml
Does anyone know how to enable the JFileChooser to accept Windows Environment Variables.
The reason I want to be able to use Environment Variables is because the TestComplete tests are going to be run on a variety of computers, and everyone might have their test files in a different location.
The JFileChooser doesn't do this automatically, but you can do it yourself by interpreting the content of filename string as returned from the JFileChooser in the accept handler.
So we have a routine to get all the environment variables, which are made into lower case to make them match more easily:
private Map<String, String> getEnv() {
Map<String, String> fromEnv = System.getenv();
Map<String, String> toReturn = new HashMap<>();
for (String key : fromEnv.keySet()) {
toReturn.put(key.toLowerCase(), fromEnv.get(key));
}
return toReturn;
}
This will be used by a routine that expands the filename, which is relatively simple - simply find the %VAR% items, and replace them. In the case of an unmatched variable, just break out, leaving the string partially parsed.
private String expandFileName(String filename) {
Pattern p = Pattern.compile("%([^%]*)%");
Matcher m = p.matcher(filename);
Map<String, String> env = getEnv();
while (m.find()) {
String var = m.group(1);
String value = env.get(var.toLowerCase());
if (value != null) {
filename = filename.replaceAll("%" + var + "%",
Matcher.quoteReplacement(value));
} else {
return filename;
}
m = p.matcher(filename);
}
return filename;
}
Next, we need to use a subclass of JFileChooser to deal with the attempt to use a filename, so we need to override the approveSelection method, get the filename, expand it and try to determine the file in question. Because this code is going to be used in an open dialog, I took some liberties in the accept routine where it requires the file to exist rather than returning with the expanded name of the file.
public void approveSelection() {
File f = getSelectedFile();
// remove the CWD from the string - leaving the text from the edit box
String prena = f.toString().replace(getCurrentDirectory().toString() + File.separator, "");
String name = expandFileName(prena);
if (prena.equals(name)) {
if (!f.exists()) {
return;
}
// This expanded to the same, and the file is there
super.approveSelection();
return;
}
// try to use the name
f = new File(name);
if (f.isFile()) { // file, ok
setSelectedFile(f);
super.approveSelection();
} else if (f.isDirectory()) { // change to dir
setCurrentDirectory(f);
return;
} else if (!f.exists()) { // try with cwd and name in field
f = new File(getCurrentDirectory(), name);
if (f.exists()) {
setSelectedFile(f);
super.approveSelection();
}
}
}
The logic is rather convoluted, but the point is to try to catch most of the conditions that you would consider.
The long and the short of it is that you have to do it manually, but the amount of work required is really not that much.
You can then glue them all into a:
JFileChooser chooser = new JFileChooser() {
// put in all the routines as listed earlier
};
chooser.setAcceptAllFileFilterUsed(true);
int choice = chooser.showOpenDialog(null);
if (choice == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getAbsolutePath();
System.out.println(name);
}
Perhaps you could dynamically generate a batch script and then execute it?
Why not just ask the user where the file is?

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?

Load and display all the images from a folder

I want to read all the images in a folder using Java.
When: I press a button in the Java application,
It should:
ask for the directory's path in a popup,
then load all the images from this directory,
then display their names, dimension types and size.
How to proceed?
I have the code for read the image and also for all image in the folder but how the things i told above can be done?
Any suggestion or help is welcome! Please provide reference links!
Untested because not on a machine with a JDK installed, so bear with me, that's all typed-in "as-is", but should get you started (expect a rush of downvotes...)
Loading all the Images from a Folder
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Test {
// File representing the folder that you select using a FileChooser
static final File dir = new File("PATH_TO_YOUR_DIRECTORY");
// array of supported extensions (use a List if you prefer)
static final String[] EXTENSIONS = new String[]{
"gif", "png", "bmp" // and other formats you need
};
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
public static void main(String[] args) {
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
// you probably want something more involved here
// to display in your UI
System.out.println("image: " + f.getName());
System.out.println(" width : " + img.getWidth());
System.out.println(" height: " + img.getHeight());
System.out.println(" size : " + f.length());
} catch (final IOException e) {
// handle errors here
}
}
}
}
}
APIs Used
This is relatively simple to do and uses only standard JDK-packaged classes:
File
FilenameFilter
BufferedImage
ImageIO
These sessions of the Java Tutorial might help you as well:
Reading/Loading an Image
How to Use Icons
How to Use File Choosers
Possible Enhancements
Use Apache Commons FilenameUtils to extract files' extensions
Detect files based on actual mime-types or content, not based on extensions
I leave UI code up to you. As I'm unaware if this is homework or not, I don't want to provide a full solution. But to continue:
Look at a FileChooser to select the folder.
I assume you already know how to make frames/windows/dialogs.
Read the Java Tutorial How to Use Icons sections, which teaches you how to display and label them.
I left out some issues to be dealt with:
Exception handling
Folders with evil endigs (say you have a folder "TryMeIAmEvil.png")
By combining all of the above, it's pretty easy to do.
javaxt.io.Directory directory = new javaxt.io.Directory("C:\Users\Public\Pictures\Sample Pictures");
directory.getFiles();
javaxt.io.File[] files;
java.io.FileFilter filter = file -> !file.isHidden() && (file.isDirectory() || (file.getName().endsWith(".jpg")));
files = directory.getFiles(filter, true);
System.out.println(Arrays.toString(files));
step 1=first of all make a folder out of webapps
step2= write code to uploading a image in ur folder
step3=write a code to display a image in ur respective jsp,html,jframe what u want
this is folder=(images)
reading image for folder'
Image image = null;
try {
File sourceimage = new File("D:\\images\\slide4.jpg");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources