Home > Enterprise >  Accessing local variable within actionPerformed Java eclipse
Accessing local variable within actionPerformed Java eclipse

Time:05-10

i am trying to reach the value within an int variable from within the actionPerformed class, the integer comes from another class where its passed as an argument "asd" and holds the value "1". I obviously deleted some lines from the code i posted below to make it easier to read but what i ve deleted has nothing to do with the problem im having. So here, the output i see is;

asd

1

1

0

0

the last two outputs are from the actionPerformed class, they appear when i click the related button. How can i make it so those 2 outputs are also shown as 1?

public class customerAppointmentScreen extends JFrame implements ActionListener{
private JButton massB,indiB;
public int asd,id;

public customerAppointmentScreen(int asd) {
    System.out.println("asd ");
    System.out.println(asd);
    id=asd;
    System.out.println(id);
    
}

public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    
    if(e.getSource()==massB) {
        int id=asd;
        System.out.println(asd);
        System.out.println(id);
        //this.setVisible(false);
    }
    else if(e.getSource()==indiB) {
        
        this.setVisible(false);
    }
}

}

CodePudding user response:

Starting with...

public int asd,id;

public customerAppointmentScreen(int asd) {
    System.out.println("asd ");
    System.out.println(asd);
    id=asd;
    System.out.println(id);
    
}

The parameter asd is never assigned to the instance field asd, so the instance field remains 0 (id on the other hand is equal to the parameter asd)

When the ActionListener is triggered...

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == massB) {
        int id = asd;
        System.out.println(asd);
        System.out.println(id);
        //this.setVisible(false);
    } else if (e.getSource() == indiB) {

        this.setVisible(false);
    }
}

You assign the instance field asd value to the local variable id, since asd is still zero, so is id.

The "simple" solution would be to assign the parameter from the constructor to the appropriate instance field OR use the correct instance field in the ActionListener, depending on your intentions.

  • Related