【问题标题】:Java GUI Action Listener with Inner Classes具有内部类的 Java GUI 操作侦听器
【发布时间】:2013-05-01 08:56:33
【问题描述】:

我正在为我的一门课程开发实验室,需要一些帮助。

我正在构建一个 Apartment Complex GUI,它将具有一个菜单系统和许多不同类之间的单独功能。该综合体由租户、员工和银行组成。

我目前有整个项目基于控制台工作,但现在我被分配将其转换为 GUI 界面。

这是我的 GUI 主函数中的代码:

   ApartmentComplex mavPlace = new ApartmentComplex(); //creates a new apartment complex object
   mavPlace.aptBank.setBalance(ANNUAL_BUDGET); //sets the apartment bank budget
   readFile(mavPlace); 

   mavPlace.goThroughAndAssignValues(mavPlace);
   JFrame frame = new JFrame("My First GUI");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(300,300);
   JButton button = new JButton("Press");
   frame.getContentPane().add(button); // Adds Button to content pane of frame
   frame.setVisible(true);

   button.addActionListener(new ActionListener()
            {
                    public void actionPerformed(ActionEvent e)
                    {
                        //Execute when button is pressed                          
                        mavPlace.lease(mavPlace);
                    }
            });

使用动作监听器,当按下按钮时,它应该调用我的另一个类中的租用函数。从那里我希望它回到控制台输出。 netbeans 给我的错误是:从内部类中访问局部变量 mavPlace;需要声明为final ....现在我进行了最后的声明,只是为了看看发生了什么并且它起作用了,但我无法编辑我的复杂细节,所以这是不可能的。

我能做什么?

谢谢!

【问题讨论】:

  • final ApartmentComplex temp = mavPlace;,并在动作监听器中使用temp 代替mavPlace

标签: java swing user-interface frame actionlistener


【解决方案1】:

让你的类实现 ActionListener 接口并使用它来添加一个动作监听器,即

button.addActionListener(this);

http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

【讨论】:

    【解决方案2】:

    如果你使用匿名类,你应该将类中使用的参数设置为当前块中的最终类型或成员私有变量。

    class MyGUI
    {
      ApartmentComplex mavPlace;
      public MyGUI()
      {
       JFrame frame = new JFrame("My First GUI");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(300,300);
       JButton button = new JButton("Press");
       frame.getContentPane().add(button); // Adds Button to content pane of frame
       frame.setVisible(true);
       mavPlace = new ApartmentComplex(); //creates a new apartment complex object
       mavPlace.aptBank.setBalance(ANNUAL_BUDGET); //sets the apartment bank budget
       readFile(mavPlace); 
    
       mavPlace.goThroughAndAssignValues(mavPlace);
       button.addActionListener(new ActionListener()
                {
                        public void actionPerformed(ActionEvent e)
                        {
                            //Execute when button is pressed                          
                            mavPlace.lease(mavPlace);
                        }
                });
    
    
    
      }
    
    
    }
    

    我认为你应该重新考虑你的程序结构。 如果你告诉我们完整的目的,你会得到更好的答案。

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2011-06-17
      • 2019-04-12
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多