Java 主类中的变量未存储在其他文件中
我是一个编程新手,我再次发布这篇文章,因为我没有找到解决问题的方法。我正在写一个包含三个文件的简单项目。在主类中,我构建gui: //AlladinLamp.javaJava 主类中的变量未存储在其他文件中,java,swing,variables,user-interface,Java,Swing,Variables,User Interface,我是一个编程新手,我再次发布这篇文章,因为我没有找到解决问题的方法。我正在写一个包含三个文件的简单项目。在主类中,我构建gui: //AlladinLamp.java import statements go here public class AlladinLamp { int fnh; JComboBox runners; other variables go here actionListener and other methods go here, inc
import statements go here
public class AlladinLamp {
int fnh;
JComboBox runners;
other variables go here
actionListener and other methods go here, including
public int getFNH() { return fnh; }
ActionListener runnersActionListener = new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
String runnersNumber = ( String )runners.getSelectedItem();
fnh = Integer.parseInt( runnersNumber );
hNam = new String[ fnh ];
hNum = new int[ fnh ];
hVal = new int[ fnh ];
jtxt = new JTextField[ fnh ];
reducedFNH = reduce( fnh );
}
};
public AlladinLamp() {
gui built here...
String[] numberOfRunners = { "8", "9", "10", "11", "12",
"13", "14", "15", "16", "17",
"18", "19", "20", "21", "22" };
runners = new JComboBox( numberOfRunners );
runners.setMaximumRowCount(5);
runners.addActionListener( runnersActionListener );
...
}
public static void main( String args[] ) {
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
AlladinLamp lamp = new AlladinLamp();
}
});
}
另一个文件未接收由runners组合框生成的值
//Process.java
import statements go here
public class Processes {
int fullNH;
AlladinLamp lamp;
public Process() {
lamp = new AlladinLamp();
fullNH = lamp.getFNH();
...
}
第二个文件中未读取变量fnh。有人能告诉我我做错了什么吗?提前谢谢。编辑:好的。您可以在第二个文件的此行上创建一个新的
AlladinLamp
lamp = new AlladinLamp();
现在,程序马上试图让FNH在这条线上
fullNH = lamp.getFNH();
问题是,如果AlladinLamp
是您的主类,那么在另一个类中调用new AlladinLamp()
将创建AlladinLamp
的新实例(一个全新的对象)。然后您尝试立即从新的AlladinLamp
获取fnh
——它将为空
您需要做的是获取现有对象AlladinLamp
,然后对其调用getFNH()
如果像这样从AlladinLamp
类开始进程
new Processes();
然后将进程
构造函数更改为
public class Processes {
AlladinLamp lamp;
int fullNH;
public Processes(AlladinLamp al) {
lamp = al;
fullNH = lamp.getFNH();
}
}
当您确实从AlladinLamp
类启动进程时,您希望这样启动它:
new Processes(this);
“不被阅读”是什么意思?你有什么错误吗?您是否没有得到您期望的结果?可能会显示创建runners
JComboBox的代码,以及在runners
中填充的值。当我在组合框中选择一个值时,它不会在第二个文件中读入fullNH。它存储在第一个文件的fnh中,但不存储在第二个文件的fullNH中。你知道为什么吗?我已经按照你的要求更新了代码。我投票决定结束这项工作,因为OP似乎需要一个关于Java中的文件与对象以及一些相关问题的教程,使得任何完整的答案对于这个环境来说都太长了。好的,我将尝试所有这些,稍后再与你联系。非常感谢。但我仍然问自己,为什么它会在第一个文件中存储在fnh中,并根据该值生成一些gui响应?哪个文件是您的主文件(起始文件)AlladinLamp.java是主类所在的位置。processs.java是另一个保存fullNH变量的文件。这可能有可变范围的东西吗???在AlladinLamp
中的哪个位置调用/启动了进程?