Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(550,550);

    input = new JFileChooser();
    add( input );
    input.addActionListener(
        new ActionListener(){
            public void actionPerformed( ActionEvent e ){
                //die();
                createFile();
            }
        }

    );

    setLayout( new FlowLayout() );

    pack();


}// end of constructor

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

public void createFile(){
    System.out.println("Hello");
}

public void die(){
    System.exit(0);
}

}// end of MFRAME CLASS

like image 803
MaCo Avatar asked Jun 10 '13 23:06

MaCo


People also ask

What does JFileChooser do in Java?

Class JFileChooser. JFileChooser provides a simple mechanism for the user to choose a file.

How do I select multiple files in JFileChooser?

JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.


1 Answers

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) {
    createFile();
} 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

like image 84
Reimeus Avatar answered Oct 10 '22 00:10

Reimeus