简体   繁体   中英

How to access a comboBox from another class in Java

comboBoxEnvIn Java is it possible to access a comboBox when it is sitting within a different class entirely?I want to use it as a whole and not just pass through it's values.

I have two classes - each has a GUI. I have my main.java (main) class and my ExportImportWindow.java

I am trying to access the comboBox that I use in my ExportImportWindow class called comboBoxEnv

Currently my code in my main class refers/uses the wrong comboBox called comboBox.

It's causing the information that is written to a file to be the incorrect information.

My code from main is this:

if (comboBox.getSelectedItem() == null ){

JOptionPane.showMessageDialog( null, "Please choose an ei");
}

else {

String env = comboBox.getSelectedItem().toString();

ExportImportWindow frm = new ExportImportWindow("Export",env,xmlFile , null, me); 

frm.setVisible( true );
}

I am unsure as to how I can get access to the correct comboBox which sits in the other class like so. I have already declared it at the top of my code as to attempt to access it within my main class.

public final JComboBox comboBoxEnv ;

public ExportImportWindow( final String mode, final String env,String FromFile,String ToFile, final Main main){

comboBoxEnv = new JComboBox();

//other code to populate comboBoxEnv
}

This is what I currently have after my last attempt did not work:

    ExportImportWindow exportImport = new ExportImportWindow(//not sure what to pass through);
    exportImport.comboBoxEnv; // trying to access the method the ComboBoxEnv sits in

I feel all the articles I look at are simply asking how to pass the values whether as I want to use the entire comboBox and not just it's values. Really appreciate any one who could share their knowledge on this. I did get access to it but it was only by creating it as a method which did not work.

You can define getter in your ImpexWindow (better) or just use the class' field because the field is public (not recommended way).

So in your ExportImportWindow you should keep a reference to the ImpexWindow where the combo box is defined and use the ImpexWindow's field

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