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);
}
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"
.