Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot assign value to "final" variable in java

Tags:

java

final

swing

 private void pushButtonActionPerformed(java.awt.event.ActionEvent evt)
{
    final int c=0;
    final JDialog d=new JDialog();
    JLabel l=new JLabel("Enter the Element :");
    JButton but1=new JButton("OK");
    JButton but2=new JButton("Cancel");
    final JTextField f=new JTextField(10);
    JPanel panel = new JPanel();
    but1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            c=Integer.parseInt(f.getText());
            d.setVisible(false);
            d.dispose( );
        }
     });
but2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        d.setVisible(false);
        d.dispose( );
    }
});
}

I am using netbeans 7.1.1. This is my code here i have declared 'c' as "final int" but the line "c=Integer.parseInt(f.getText());" i am getting an error "cannot assign a value to a final variable". If i am deleting the word final from the declaration and making it just as "int c" then in the same line i get an error "local variable c cannot be accessed from within a class;needs to be declared final". can anyone tell me why is this happening ?

like image 938
rick Avatar asked Apr 16 '12 12:04

rick


1 Answers

You've got c declared in a function, and then you've created an anonymous inner class within that function. This inner class, the ActionListener, persists past the time your function terminates - so it can't assign values to c, because c is local to the function.

The warning about "final" is misleading - that's just the compiler telling you that you can't access transient local variables from an anonymous class. You can't solve the problem just by making c final, as that would prevent any assignment to it at all, but you can make c an instance member of the class pushButtonActionPerformed is in, instead. Something like this:

class Something
{
    int c;

    private void pushButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        JButton but1=new JButton("OK");
        but1.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                c=Integer.parseInt(f.getText());
            }
        });
    }
}
like image 182
banana Avatar answered Nov 01 '22 23:11

banana