简体   繁体   English

如何从Java中的另一个类访问comboBox

[英]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. comboBoxEnvIn Java是否可以在完全位于另一个类中时访问comboBox?我想整体使用它,而不仅仅是传递它的值。

I have two classes - each has a GUI. 我有两个类-每个类都有一个GUI。 I have my main.java (main) class and my ExportImportWindow.java 我有main.java(主要)类和ExportImportWindow.java

I am trying to access the comboBox that I use in my ExportImportWindow class called comboBoxEnv 我正在尝试访问在我的名为comboBoxEnv的ExportImportWindow类中使用的comboBox

Currently my code in my main class refers/uses the wrong comboBox called comboBox. 当前,我在主类中的代码引用/使用了错误的comboBox,称为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. 我不确定如何才能访问位于另一个类中的正确comboBox。 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. 我觉得我看过的所有文章都只是在问如何传递值,就像我想使用整个comboBox一样,而不仅仅是它的值。 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). 您可以在ImpexWindow中定义getter(更好),也可以只使用class的字段,因为该字段是公共的(不建议这样做)。

So in your ExportImportWindow you should keep a reference to the ImpexWindow where the combo box is defined and use the ImpexWindow's field 因此,在ExportImportWindow ,应保留对定义组合框的ImpexWindow的引用,并使用ImpexWindow's字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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