简体   繁体   English

如何将ActionListener添加到动态创建的JButton中?

[英]How add ActionListener to dynamically created JButton?

I want to dynamically create a JFrame with a text field and two buttons. 我想动态创建一个带有文本字段和两个按钮的JFrame The problem is that JTextField is not visible inside the ActionListener of JButton ( treePanel.addObject(txt.getText()); ). 问题是JTextFieldJButtonActionListenertreePanel.addObject(txt.getText()); )内部不可见。 How to solve this issue? 如何解决这个问题?

JButton addButton = new JButton("Add");
        addButton.setActionCommand(ADD_COMMAND);
        addButton.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent event) 
            {
                JFrame f = new JFrame("Add new group/subgroup");
                JPanel p = new JPanel(new MigLayout());
                p.add(new JLabel("Group/subgroup name: "));
                JTextField txt = new JTextField(10);
                JButton ok = new JButton("Ok");
                JButton cancel = new JButton("Cancel");
                p.add(txt,"wrap");
                p.add(ok); 
                p.add(cancel);
                f.add(p);

                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);                    
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
                ok.addActionListener(new ActionListener() 
                {
                    @Override
                    public void actionPerformed(ActionEvent event)
                    {
                        treePanel.addObject(txt.getText()); 
                    }
                });
                cancel.addActionListener(new ActionListener() 
                {
                    @Override
                    public void actionPerformed(ActionEvent event)
                    {
                        f.dispose();    
                    }
                });
            }
        });

Anonymous classes is an inner classes and the strict rule applies to inner classes (JLS 8.1.3) : 匿名类是一个内部类 ,严格规则适用于内部类 (JLS 8.1.3)

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final . 必须将任何未在内部类中声明的局部变量,形式化方法参数或异常处理程序参数声明为final Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class . 必须在内部类主体之前明确分配在内部类中使用但未声明的任何局部变量。

So in your case you need to change the txt to be a final regarding the above rule. 因此,根据您的情况,您需要将txt更改为上述规则的最终版本。

final JTextField txt = new JTextField(10);

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

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