Reputation: 382
Can we initialize instance variable through JTextField? For example, lets x is an instance variable and i want to initialize its value when jbutton is clicked. i want to use this x, in another method. so can we update x.
public class CT extends JFrame{
JTextField txtf = new JTextField(20);
JButton btn = new JButton("Click");
JLabel lbl = new JLabel();
int x;
CT(){
setSize(600, 400);
setVisible(true);
setLayout(new FlowLayout());
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int a =Integer.parseInt(txtf.getText());
display(a);
x=a;
}
});
add(btn);
add(txtf);
add(lbl);
}
public void display(int s){
System.out.println(s);
System.out.println(x); //this display zero?? can we update it?
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new CT();
}
}
Upvotes: 2
Views: 178
Reputation: 711
The statement
x=a;
should be executed before the statement
display(a);
You are printing out the values of a and x before you 'initialize' x.
Upvotes: 1
Reputation: 34628
The reason it displays 0
is that you call
display(a);
x=a;
Instead of
x=a;
display(a);
However, in either case, this is not initialization. This is simply assignment. The field x
is not set to anything (well, it's 0, the default) when the constructor of CT
is finished.
It's important to note that the code in actionPerformed()
is not really called in the constructor, only created in it. So any assignments inside it are not considered "initialization".
What is the difference between an initialization and an assignment? If x
was final
, then the only place where you can put a value in it is
Initializer. E.g.
final int x = 15;
Initialization block. E.g.
final int x;
{
x = 15;
}
So these are considered "initializations". All other assignments to a final x
, in methods, in methods of nested classes etc. would fail.
Since you did not declare x
as final
you may not notice the difference between an initialization and an assignment, but what you have there in your code is definitely an assignment.
Upvotes: 0