You are here:

Java/Calling a file selected in new button in Java


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

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();

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.


All Answers

Answers by Expert:

Ask Experts


Artemus Harper


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


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#

Washington State University

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

©2016 All rights reserved.