возвращать значение при вызове события JButton actionperformed

У меня возникла проблема с событиями действия JButton, я объявил глобальную переменную (boolean tc1) и файл JButton t1. Когда я нажимаю JButton, мне нужно изменить значение логической переменной на «истина». Может кто-нибудь мне помочь? Мой код идет сюда.

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


    }
}

Спасибо.


person ram    schedule 16.02.2013    source источник
comment
В чем проблема с вашим кодом? Что не работает?   -  person qben    schedule 16.02.2013


Ответы (4)


tc1 должна быть переменной экземпляра.
Вы можете использовать локальную переменную в другом классе, определенном внутри метода, если локальная переменная не является переменной final.
Удалите объявление tc1 из constructor для видимости целый 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..


   }
}

Я также уже столкнулся с этой проблемой и, к счастью, нашел решение

person Govind Balaji    schedule 16.02.2013

Вы не можете изменить значение переменной локального метода в анонимном внутреннем классе (слушателе действия). Однако вы можете изменить переменную экземпляра внешнего класса... так что вы можете просто переместить tc1 в Tracker.

class Tracker extends JPanel {
    public static void main(String[] args) {
        new Tracker();
    }

    private boolean tc1; // <=== class level instead...

    public Tracker() {

        JButton t1 = new JButton(" ");

        t1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tc1 = true;
            }
        });
    }
}
person Adam    schedule 16.02.2013

Прежде всего, вы сказали, что i have declared a global variable(boolean tc1), здесь tc1 не является глобальной переменной, если вам нужна глобальная переменная, вы должны объявить эту переменную как static.

Затем, если вы хотите получить доступ к этой переменной на button click event, вы можете написать следующий код:

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;
            getValue();
        }
        });
    }
    public void getValue()
    {
        System.out.println("values is: "+ tc1);
    }
}
person Bhushan    schedule 16.02.2013

Определить обработчик кликов:

public void onClick(Boolean tc1){
  System.out.println(tc1) ;
  //Write some logic here and use your updated variable
}

А потом:

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 ;
          onClick(tc1) ;
      }
});
person vikingmaster    schedule 16.02.2013