Klausos Klausos
Klausos Klausos

Reputation: 16050

How add ActionListener to dynamically created JButton?

I want to dynamically create a JFrame with a text field and two buttons. The problem is that JTextField is not visible inside the ActionListener of JButton (treePanel.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();    
                    }
                });
            }
        });

Upvotes: 0

Views: 1021

Answers (1)

Salah
Salah

Reputation: 8657

Anonymous classes is an inner classes and the strict rule applies to inner classes (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. 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.

final JTextField txt = new JTextField(10);

Upvotes: 3

Related Questions