Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

java - return a value when an JButton actionperformed event is called

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...