cannot assign value to “final” variable in java

2019-02-06 06:51发布

 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 ?

标签: java swing final
7条回答
Fickle 薄情
2楼-- · 2019-02-06 07:41

final makes the "variable" a constant--you can't change it. As to why the compiler is giving you warnings after you delete the final keyword, we'd need to see the whole code...

EDIT:

 but1.addActionListener(new ActionListener()
 {
     public void actionPerformed(ActionEvent e)
     {
         c=Integer.parseInt(f.getText());
         d.setVisible(false);
         d.dispose( );
     }
  });

I believe this is the segment of code that causes the compiler to fire the warning. You can't use c in this class...

查看更多
登录 后发表回答