You are here:

Java/Calling a file selected in new button in Java

Advertisement


Question
I have a program that have 2 buttons. One button is for selecting a file (using JFileChooser) and the other button is for performing an action for the file chosen (e.g. hash). To do this, I used the ActionPerformed method.

For example, the program will look something like this:

File: _________________ Select File
Hash

My question now is how do I link the second button (Hash) to the first button (Select File) so that when I press the Hash, it will perform the hash function on the file chosen.

The code I used for the Select File button is this:

int retval = _fileChooser.showOpenDialog(textField);
if (retval == JFileChooser.APPROVE_OPTION)
{
   File file = _fileChooser.getSelectedFile();
   textField.setText(file.getName());
}

Answer
You put the file variable outside of the method in the class as a field, in the same way you have _fileChooser as a field.

Just make sure you check the file for null in case the user clicks the hash button before the file selection button.

If you have multiple classes, you will need to have one class with a reference to the other one (that you pass in via a constructor) that you can change via one of the class methods you define.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.