Search code examples
javaswingjbutton

How to Access one variable from a jButtonActionPerformed to another jButtonActionPerformed


I want to print a variable in a jButtonActionPerformed which is in another jButtonActionPerformed. please suggest me how can I do this.

I implemented two jButtonActionPerformed(). Please have a look on the following code.

     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    String d = scheme.getText();
    String e = workspace.getText();

    System.out.println(d);
    System.out.println(e);


    // ****** Here I want to print chooser.getSelectedFile() ****


}                                       

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Select Source Directory");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
  //System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
  System.out.println("Your Source Directory: " + chooser.getSelectedFile());

} else {
  System.out.println("No Selection ");
}

//Getting Current Working Directory
String cwd = System.getProperty("user.dir");
System.out.println("Current working directory : " + cwd);
}

Solution

  • Define a class member varaible to use it from various methods of the class. A rough sketch of what would work for you looks like this:

    public class YourClass {
        private JFileChooser chooser = new JFileChooser();
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  
            //print chooser.getSelectedFile()
        }                                      
    
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { 
            //choose file
        }
    }