简体   繁体   中英

Get value from ActionListener from one class for use in another Class

I'm having an issue with ActionListeners.

Currently I am generating an organismId in one class when a button is pressed. I want to use this generated organismId in another class though this is where I'm having problems.

This is a snippet of my code: 1st Class:

public void actionPerformed(ActionEvent e) {
 String item = (String) mainComboBox.getSelectedItem();
    Object o = subItems.get(item);
    String organismComboItem = (String) subComboBox.getSelectedItem();

 // Inserts relevant organisms into subComboBox
    if (treeArray.contains(organismComboItem)) {
        //System.out.println(treeArray.indexOf(organismComboItem));
        String selectedId = idArray.get(treeArray.indexOf(organismComboItem));
        organismId = selectedId;
         setOrganismId(organismId);

    }
}

public String getOrganismId() {
return organismId;
}
public void setOrganismId(String orgId) {
organismId = orgId;
}

2nd Class:

private MyListener 
number = new MyListener();
    String organismId = number.getOrganismId();

Currently organismId is still displaying as null in my second class as opposed to the value that is generated from the first class.

I'm sure there's a relatively simple solution and have spent much time trying to research it though nothing I found seemed to work thus this is my last resort.

Here are my 2 classes in full:

Class 1:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;

public class MyListener implements ActionListener{

private int clickCount = 0;

private JButton addButton;
private JButton subtractButton;
private JLabel label;
private JComboBox mainComboBox;
private JComboBox subComboBox;
public static String organismId;



private Hashtable subItems = new Hashtable();
private ArrayList<String> treeArray = new ArrayList<String>();
private ArrayList<String> idArray = new ArrayList<String>();
private ArrayList<String> chromalveolataIDArray = new ArrayList<String>();
private ArrayList<String> metazoaIDArray = new ArrayList<String>();
private ArrayList<String> mycetozoaIDArray = new ArrayList<String>();
private ArrayList<String> viridiplantaeIDArray = new ArrayList<String>();
private ArrayList<String> virusesIDArray = new ArrayList<String>();
private TreeSet<String> chromalveolataTreeSet = new TreeSet<String>();
private TreeSet<String> viridiplantaeTreeSet = new TreeSet<String>();
private TreeSet<String> metazoaTreeSet = new TreeSet<String>();
private TreeSet<String> mycetozoaTreeSet = new TreeSet<String>();
private TreeSet<String> virusesTreeSet = new TreeSet<String>();


String[] treeItems = {"Select Tree", "Chromalveolata", "Metazoa",     "Mycetozoa", "Viridiplantae", "Viruses"};

 public MyListener(){

 } 

   public MyListener(JButton addButton, JLabel label, JComboBox   mainComboBox,   JComboBox subComboBox,  JButton subtractButton){
    this.addButton = addButton;

    this.label = label;
    this.mainComboBox = mainComboBox;
    this.subComboBox = subComboBox;
    this.subtractButton = subtractButton;

    BufferedReader bReader = null;
    try {
        bReader = new BufferedReader(new FileReader("organisms.txt"));
        //ArrayList<Person> peopleList = new ArrayList<Person>();
        // bReader.readLine(); // this will read the first line
        String line = null;
        ArrayList<String> organismIdArray = new ArrayList<String>();
        ArrayList<String> organismArray = new ArrayList<String>();



        TreeSet<String> treeSet = new TreeSet<String>();

        while ((line = bReader.readLine()) != null) {
 String[] treeItems = {"Select Tree", "Chromalveolata", "Metazoa",     "Mycetozoa", "Viridiplantae", "Viruses"};
            String[] peopleInfo = line.split("\\t|\\;");
            // System.out.println(peopleInfo[3]);

            String id = ">" + peopleInfo[0];
            String organism = peopleInfo[2];
            String tree = peopleInfo[3];

            treeArray.add(organism);
            idArray.add(id);
            //System.out.println(treeArray);
            // System.out.println(organism);

            populateSubCombo("Chromalveolata", chromalveolataTreeSet, tree,  organism);
            populateSubCombo("Metazoa", metazoaTreeSet, tree, organism);
            populateSubCombo("Mycetozoa", mycetozoaTreeSet, tree, organism);
            populateSubCombo("Viridiplantae", viridiplantaeTreeSet, tree, organism);
            populateSubCombo("Viruses", virusesTreeSet, tree, organism);

            populateOrganismID("Chromalveolata", tree, chromalveolataIDArray, id);
            populateOrganismID("Metazoa", tree, metazoaIDArray, id);
            populateOrganismID("Mycetozoa", tree, mycetozoaIDArray, id);
            populateOrganismID("Viridiplantae", tree, viridiplantaeIDArray, id);
            populateOrganismID("Viruses", tree, virusesIDArray, id);

            organismIdArray.add(id);
            organismArray.add(organism);
            treeSet.add(tree);

            String[] defaultItems = {"> Please Select a Tree"};
            subItems.put(treeItems[0], defaultItems);

            String[] chromalveolataItems = chromalveolataTreeSet.toArray(new   String[chromalveolataTreeSet.size()]);
            subItems.put(treeItems[1], chromalveolataItems);

            String[] mycetozoaItems = mycetozoaTreeSet.toArray(new String[mycetozoaTreeSet.size()]);
            subItems.put(treeItems[3], mycetozoaItems);

            String[] metazoaItems = metazoaTreeSet.toArray(new String[metazoaTreeSet.size()]);
            subItems.put(treeItems[2], metazoaItems);

            String[] viridiplantaeItems = viridiplantaeTreeSet.toArray(new String[viridiplantaeTreeSet.size()]);
            subItems.put(treeItems[4], viridiplantaeItems);

            String[] virusesItems = virusesTreeSet.toArray(new String[virusesTreeSet.size()]);
            subItems.put(treeItems[5], virusesItems);

        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MatureDataOutput.class.getName()).log(Level.SEVERE, null, ex);

    } catch (IOException ex) {
        Logger.getLogger(Dissertation1.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            bReader.close();
        } catch (IOException ex) {
             Logger.getLogger(MatureDataOutput.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

public void actionPerformed(ActionEvent e) {
 String item = (String) mainComboBox.getSelectedItem();
    Object o = subItems.get(item);
    String organismComboItem = (String) subComboBox.getSelectedItem();

 // Inserts relevant organisms into subComboBox
    if (treeArray.contains(organismComboItem)) {
        //System.out.println(treeArray.indexOf(organismComboItem));
        String selectedId = idArray.get(treeArray.indexOf(organismComboItem));
        organismId = selectedId;
         setOrganismId(organismId);

    }
    if (o == null) {
        subComboBox.setModel(new DefaultComboBoxModel());

    } else {
        subComboBox.setModel(new DefaultComboBoxModel((String[]) o));
    }

    if(e.getSource() == addButton){
        clickCount++;
    }
    else if(e.getSource() == subtractButton){
        System.out.println(organismId);
    }


    label.setText("You've clicked " + clickCount + " times.");

}


public static TreeSet<String> populateSubCombo(String orgName,     TreeSet<String> treeSet, String tree, String organism){


            if (orgName.equals(tree)) {
                treeSet.add("- Please Select An Organism");
                treeSet.add(organism);
             //   list.add(id);

                //  System.out.println(viridiplantaeOrganismArray);
            }

return treeSet;


} 

public static ArrayList<String> populateOrganismID(String orgName, String tree, ArrayList<String>list, String id){

    if (orgName.equals(tree)) {
               list.add(id);

} return list;
}   


public static void setOrganismId(String orgId) {
organismId = orgId;
}

public String getOrganismId() {
return organismId;
}


}

Class 2:

import static dissertation1.Dissertation1.average;
import static dissertation1.Dissertation1.gcPerc;
import static dissertation1.Dissertation1.max;
import static dissertation1.Dissertation1.min;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class MyListener1 implements ActionListener {

private final JFileChooser fileChooser;
private BufferedReader br;

private final JTextField maxMiRNALength;
private final JTextField minSRNALength;
private final JTextField gcPercMIRNA;
private final JTextField minHairpinLength;
String currentLine;


ArrayList<Integer> hairpinOrganisms = new ArrayList<Integer>();
ArrayList<Integer> matureOrganisms = new ArrayList<Integer>();
ArrayList<Integer> matureGcContent = new ArrayList<Integer>();


private JButton openMatureButton;
private JButton openHairpinButton;
private JButton generateParametersButton;

private File hairpinFile;
private File matureFile;
int returnVal;

private MyListener number;


public MyListener1(JButton openMatureButton, JButton openHairpinButton,     JButton generateParametersButton, JTextField maxMiRNALength, JTextField minSRNALength, JTextField gcPercMIRNA, JTextField minHairpinLength){
    this.openMatureButton = openMatureButton;
    this.openHairpinButton = openHairpinButton;
    this.generateParametersButton = generateParametersButton;
    this.maxMiRNALength = maxMiRNALength;
    this.minSRNALength = minSRNALength;
    this.gcPercMIRNA = gcPercMIRNA;
    this.minHairpinLength = minHairpinLength;



    fileChooser = new JFileChooser();
}

public void actionPerformed(ActionEvent e) {
    ArrayList<Integer> gcOrgPerc = new ArrayList<Integer>();
    //number = new MyListener();
    String organismId = MyListener.organismId;
  //  String organismId = number.getOrganismId();
          //  System.out.println(treeArray);

   // ArrayList<String> organismsString = new ArrayList<String>();

    boolean printLines = false;
    StringBuilder organism = new StringBuilder();



    if (e.getSource() == openHairpinButton) {
        returnVal = fileChooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            hairpinFile = fileChooser.getSelectedFile();
            //File[] file = hairpinFileChooser.getSelectedFiles();
            //read file
            //System.out.println(organismId);
            System.out.println(organismId);
        }
    } 

    else if (e.getSource() == openMatureButton) {
        returnVal = fileChooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            matureFile = fileChooser.getSelectedFile();
            //File[] file = hairpinFileChooser.getSelectedFiles();
            //read file


        }
    }
    else if (e.getSource() == generateParametersButton){


        try {
                br = new BufferedReader(new FileReader(hairpinFile));
        } catch (Exception error) {
                error.printStackTrace();
//minHairpinLength.setText(" ");
            }
        try{
                //if (file.getName().matches("hairpin.fa") ||   file.getName().matches("high_conf_hairpin.fa")) {

                while ((currentLine = br.readLine()) != null) {
                    if (printLines) {
                        if (currentLine.startsWith(">")) {
                            // We have reached the next organism, so stop   printing
                            printLines = false;


                            organism.setLength(0);

                        } else {
                            // We are still printing the current organism
                            organism.append(currentLine);

                        }
                    }

                    if (currentLine.startsWith(organismId)) {
                            // Print this line, and start printing all lines   after this (we don't want to append the current line)
                        //organism.append(currentLine);
                        printLines = true;
                            //won't need this following line - used as error   control

                            //organisms.add(organism.length());
                        //label.setText("Min is" + min(organisms));
                    }



                }
            } catch (Exception error) {
                 error.printStackTrace();
//minHairpinLength.setText(" ");
            }

        try {
                br = new BufferedReader(new FileReader(matureFile));

                while ((currentLine = br.readLine()) != null) {
                    if (printLines) {
                        if (currentLine.startsWith(">")) {
                            // We have reached the next organism, so stop printing
                            printLines = false;
                            // Add the current organism to our collection
                            matureOrganisms.add(organism.length());
                               // Student student = new   Student(organismComboItem, organism.length(), gcPerc(organism), 25);

                            organism.setLength(0);
                        } else {
                            // We are still printing the current organism
                            organism.append(currentLine);
                        }
                    }

                    if (currentLine.startsWith(organismId)) {
                            // Print this line, and start printing all lines after this (we don't want to append the current line)
                        //organism.append(currentLine);
                        System.out.println(organismId);
                        printLines = true;

                    }




                }
            } catch (Exception error) {
                error.printStackTrace();
            }

        minHairpinLength.setText("" + min(hairpinOrganisms));
       // minHairpinLength.setBackground(Color.white);

                    maxMiRNALength.setText("" + max(matureOrganisms));
                    maxMiRNALength.setBackground(Color.red);

                    minSRNALength.setText("" + min(matureOrganisms));
                    minSRNALength.setBackground(Color.red);

                    gcPercMIRNA.setText("" + average(matureGcContent));
                    gcPercMIRNA.setBackground(Color.red);

                    System.out.println(hairpinOrganisms);
}
}}

Any help would be much appreciated! :)

Yous should probably have reference to your MyListener1 class in MyListener to be able to set organismId to it, when action is performed.

public class MyListener implements ActionListener {
    ...
    ActionListener myListener1;
    ...
    public MyListener(..., ActionListener myListener1){
        this.myListener1 = myListener1;
        ...
    }

    public void actionPerformed(ActionEvent e) {
        // logic of getting organismId is here
        myListener1.setOrganismId(organismId)
        ...
    }


public class MyListener1 implements ActionListener {
   ...
   String organismId;
   ...
   public void setOrganismId(String organismId) {
       this.organismId = organismId
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM