return a value when an JButton actionperformed event is called

ram picture ram · Feb 16, 2013 · Viewed 16.1k times · Source

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.

Answer

Govind Balaji picture Govind Balaji · Feb 16, 2013

tc1 must be an instance 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 the constructor to the visibility of whole class

  class Tracker extends JPanel {
  boolean tc1=false,tc2=false,tc3=false,tc4=false;
  public static void main(String[] args) {
    new Tracker();    
  }

public Tracker() {

    JButton tr=new JButton("TRACKER APPLET");
    JButton rf=new JButton("REFRESH");

    
    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..


   }
}

I have also encountered this problem already and luckily I found the solution