java final 赋值_无法为java中的" final" 变量赋值 (cannot assign value to "final" variable in java)...

在Java编程中,遇到一个关于final变量的问题。在事件监听器中尝试将`JTextField`的输入值赋给声明为final的变量`c`时,出现错误提示。如果去掉final关键字,又会导致局部变量不能在匿名内部类中访问。这个问题涉及到Java中final变量的作用域和使用规则。解决方案可能涉及到理解final变量如何在匿名内部类中使用。

2012-04-16 12:27:15

4

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 ?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值