MaCo MaCo -4 years ago 80
Java Question

JFileChooser - regarding the "open" and "cancel" buttons. Java

I am having some trouble using the JFileChooser. Whenever I run the program if I click the "cancel" button right away without selecting a file it will display "hello" and if I click open, it will not do anything. On other hand, if I select a file and click open it will start to display "Hello" (call the createFile method) and will display "hello" if I click "cancel".

My question is how can I find out which button was clicked and to do a specific thing for each like call the die function when clicked cancel and call the createFile function when open is clicked.

I was thinking of something like

if(e.getSource() == "Something_I_Dont_know") { do this}

Here is my code:

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Grading{

public static void main(String[] arg){

new MFrame();


}// end of class Grading

class MFrame extends JFrame{

private JCheckBox cum,uc,ucs;
private JButton calc, clear, exit;
private ButtonGroup bg;
private JTextArea display;
private JFileChooser input;

public MFrame(){

setVisible( true );

input = new JFileChooser();
add( input );
new ActionListener(){
public void actionPerformed( ActionEvent e ){


setLayout( new FlowLayout() );


}// end of constructor

public double gpa(){
return 1.0;
}// end of gpa method

public void createFile(){

public void die(){

}// end of MFRAME CLASS

Answer Source

Use the result of the appropriate showDialog method to determine which button was clicked

JFileChooser input = new JFileChooser();
int result = input.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
} else if (result == JFileChooser.CANCEL_OPTION) {
    System.out.println("Cancel was selected");

Note: Clicking the X button on the JFileChooser dialog also triggers the CANCEL_OPTION.

Read How to Use File Choosers

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download