1

我包括我的代码片段。变量 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

}

// 更多代码

} 课程结束

4

3 回答 3

0

最后不见了}

我曾经给出的最简单的答案:-D

于 2013-03-07T08:27:53.653 回答
0

问题是 fnh 的值在您要打印时仍然为空。它第一次获得值是在 actionperfomed 方法中。

于 2013-03-07T08:29:29.163 回答
0

You register your actionListener, and after that you output fnh. It has not changed yet, since no action was performed, so your listener was not called.

Maybe it's easier to understand like this:

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 );
    }
}
于 2013-03-07T08:41:47.320 回答