我包含了我的代码。变量fnh是用类范围声明的(在类定义之后)。然而,我不能用最后的陈述打印出来。如果放在actionPerformed方法内部,它会打印变量的值,但不在其外部。可能是什么问题?任何及时的建议将不胜感激。
public class Lamp {
int fnh;
Lamp() {
// More code 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( new ActionListener() {
@Override
public void actionPerformed( ActionEvent ae ) {
String runnersNumber = ( String )runners.getSelectedItem();
fnh = Integer.parseInt( runnersNumber );
reducedFNH = reduce( fnh );
}}
);
middle.add( runners );
System.out.println( fnh );
// More code here
}
//更多代码
}课程结束
答案 0 :(得分:0)
最后遗失}
。
我给过的最简单的答案:-D
答案 1 :(得分:0)
问题是fnh的值在您想要打印时仍为空。第一次获取值是在actionperfomed方法中。
答案 2 :(得分:0)
您注册了actionListener,然后输出fnh
。
它还没有改变,因为没有执行任何动作,因此没有调用你的监听器。
也许这样容易理解:
public class Lamp {
int fnh;
...
private ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed( ActionEvent ae ) {
// This is only called, when user performs an action on runners
String runnersNumber = ( String )runners.getSelectedItem();
fnh = Integer.parseInt( runnersNumber );
}};
public Lamp() {
...
runners = new JComboBox(numberOfRunners);
runners.addActionListener(actionListener);
System.out.println( fnh );
}
}