I have some problem with JButton
action events, I have declared a global variable (boolean tc1
) and a JButton t1
. When I press the JButton I need to change the value of the boolean variable to 'true'. Can any one help me out? My code goes here.
class Tracker extends JPanel {
public static void main(String[] args) {
new Tracker();
}
public Tracker() {
JButton tr=new JButton("TRACKER APPLET");
JButton rf=new JButton("REFRESH");
boolean tc1=false,tc2=false,tc3=false,tc4=false;
JButton t1=new JButton(" ");
t1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tc1=true;
}
});
System.out.println(tc1);
//remaining part of the code...
// here i need to use the value of tc1 for further process..
}
}
Thanks.
Define click handler:
And then:
tc1
must be a global variable.You can use a local variable in an another class defined inside the method, unless the local variable is a
final
variable.Take out the declaration of
tc1
from theconstructor
to the visibility of wholeclass
I have also encountered this problem already and luckily I found the solution
First of all you said that
i have declared a global variable(boolean tc1)
, here tc1 is not a global variable, if you want a global variable then you must declare that variable asstatic
.Then if you want to access that variable on
button click event
then you can write following code:You cannot change the value of a local method variable in an anonymous inner class (the action listener). You can however change an instance variable of the outer class... so you could just move tc1 to Tracker.