1

I'm new to Java. I searched for this, but didn't find a clear answer.

Is there a way to change the value of a predefined variable inside of a void method and use the new value by another void method?

What I need: In Eclipse WindowBuilder, clicking a button should change the value of a variable defined outside of this button. So I can use the new value when clicking another button. However, what happens is that when I click the other button, the initially defined value is used, and not the changed one.

Update: Sample Code:

private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        String x = "0";

        JButton btn1 = new JButton("Button 1");
        btn1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String x = "1";
                textField1.setText(x);              
            }
        });
        btn1.setBounds(102, 134, 89, 23);
        frame.getContentPane().add(btn1);

        JButton btn2 = new JButton("Button 2");
        btn2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField2.setText(x);
            }
        });
        btn2.setBounds(232, 134, 89, 23);
        frame.getContentPane().add(btn2);

        textField1 = new JTextField();
        textField1.setBounds(159, 85, 86, 20);
        frame.getContentPane().add(textField1);
        textField1.setColumns(10);

        textField2 = new JTextField();
        textField2.setColumns(10);
        textField2.setBounds(159, 179, 86, 20);
        frame.getContentPane().add(textField2);
    }

enter image description here

So here x is initialized as "0". Clicking button 1, changes x to "1". Then, clicking button 2, gives the initialized value which is "0" and not "1".

AhmedWas
  • 1,205
  • 3
  • 23
  • 38
  • 1
    if this is a static or instance variable, yes, if it is local, no. EDIT : Please define _predifined variable_ with word and/or small code – AxelH Feb 15 '17 at 06:35
  • 1
    If it is not a primitive and not immutable - please show code – Scary Wombat Feb 15 '17 at 06:35
  • 1
    Welcome to Stack Overflow! Please review our [SO Question Checklist](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) to help you to ask a good question, and thus get a good answer. – Joe C Feb 15 '17 at 06:37
  • 1
    It would be helpful If you provide the code. Having said you want to access a variable outside a method, class level variables accessed at all levels within class. Hope it helps! – fabfas Feb 15 '17 at 06:40
  • 1
    You have to define your variable outside this method in your class definition. So you can use it with your buttons. – IQV Feb 15 '17 at 06:44
  • Thanks all for commenting, please check the updated code – AhmedWas Feb 15 '17 at 06:44

3 Answers3

3

In your code, you are using a local variable x

JButton btn1 = new JButton("Button 1");
    btn1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            final String x = "1";
            textField1.setText(x);              
        }
    });

This variable will not exist outside of the inner class method ActionListener.actionPerformed you've declared.

You need to declare your variable in a scope that match your need.

In this case, you need to use a variable instance (see the Note below), so declare String x outside the method initialize to be part of the instance.

String x; //instance variable to be shared
private void initialize() {
    ...
    JButton btn1 = new JButton("Button 1");
    btn1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            x = "1";
            textField1.setText(x);              
        }
    });

    JButton btn2 = new JButton("Button 2");
    btn2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            textField2.setText(x);
        }
    });

}

Note : You can't simply put it in the initialize method since you will need to put it as final to be used inside an inner class but you are setting a value to it so it is not possible in your case.

PS :

Just notice that you were shadowing String x of the initialize method

String x = "0";

JButton btn1 = new JButton("Button 1");
btn1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String x = "1";
        textField1.setText(x);              
    }
});

In the click method, this will not use the x that was currently "0", it will be a completly different instance (even if there are named the same). So you will need to remove that declaration too since you would be hidding the instance variable I have just declare.

What are Shadow Variables in Java

But a short description would be :

A variable is shadowed if there is another variable with the same name that is closer in scope

A small example to show this shadowing would be

public class Main {

    String x = "a";
    public static void main(String[] args) {
        new Main();
    }

    public Main(){
        System.out.println(x); //"a"
        String x = "b";
        System.out.println(x); //"b"
        new Thread(new Runnable() {
            public void run() {
                String x = "c"; 
                System.out.println(x); //"c"
            }
        }).start();
        System.out.println(x); //"b"
    }

    public void method(){
        System.out.println(x); //"a"
    }
}
Community
  • 1
  • 1
AxelH
  • 14,325
  • 2
  • 25
  • 55
  • Thanks for the answer, but I removed `final` and used `String` only, but still doesn't work. – AhmedWas Feb 15 '17 at 06:52
  • With final you declare a constant. As AxelH mentioned you still define a new variable. Remove String, too. – IQV Feb 15 '17 at 06:54
  • @AhmedWas I have add a interesting thing to my answer, I have notice that you already define `String x` inside the method, so you should check the edit. If this is not clear (not sure how to explain this), tell me, I will try to reformulate this. – AxelH Feb 15 '17 at 07:19
  • @AxelH, thanks man for the detailed answer. Now everything works :) – AhmedWas Feb 15 '17 at 07:28
1

The variable would have to be defined as an instance variable of the class rather than a local variable within the method. This way all of the buttons will be able to access the variable rather than just those encapsulated within the method.

Edit:

Here's some example code to show exactly what I mean. Currently you're defining the variable x like this:

final void initialize(){
    String x = "0"; //x is defined within the scope of this method only.
} 

This constrains the variable x to only be stored within the initialize method. For your case however you would want to define x as such:

String x; //Instance variable which is available to the entire class
final void initialize(){
    x = "0"; //modifies the instance variable for the entire class 
}
iSeeJay
  • 783
  • 2
  • 6
  • 13
0

You are declaring a NEW variable x, that is the problem. Instead you should change x and define it as a member variable (as said by IQV in a comment below this answer).

public void actionPerformed(ActionEvent e) {
    final String x = "1"; // this should be x = "";
    textField1.setText(x);
}
kamehl23
  • 522
  • 3
  • 6
  • But I recommend to define `x` outside of `initialize()` as a class variable. Otherwise you can use `x`only in this method. – IQV Feb 15 '17 at 06:48