我是Java新手。我进行了搜索,但是没有找到明确的答案。
有没有办法在void方法内部更改预定义变量的值,并通过另一种void方法使用新值?
我需要什么:在Eclipse WindowBuilder中,单击按钮应更改在此按钮外部定义的变量的值。因此,我可以在单击另一个按钮时使用新值。但是,发生的是,当我单击另一个按钮时,将使用最初定义的值,而不是更改后的值。
更新:示例代码:
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);
}
因此,此处
x
初始化为"0"
。单击按钮1,将x
更改为"1"
。然后,单击按钮2,给出的初始化值为"0"
而不是"1"
。 最佳答案
在您的代码中,您正在使用局部变量x
JButton btn1 = new JButton("Button 1");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String x = "1";
textField1.setText(x);
}
});
在您声明的内部类方法
ActionListener.actionPerformed
之外,该变量将不存在。您需要在符合您需要的范围内声明变量。
在这种情况下,您需要使用一个变量实例(请参见下面的注释),因此在方法
String x
之外声明initialize
作为该实例的一部分。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);
}
});
}
注意:您不能简单地将其放在
initialize
方法中,因为您需要将其作为final
放在内部类中使用,但是您正在为其设置值,因此在您的情况下是不可能的。PS:
请注意,您正在隐藏
String x
方法的initialize
String x = "0";
JButton btn1 = new JButton("Button 1");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String x = "1";
textField1.setText(x);
}
});
在click方法中,这将不使用当前为
x
的"0"
,它将是完全不同的实例(即使名称相同)。因此,您还将需要删除该声明,因为您将隐藏我刚刚声明的实例变量。What are Shadow Variables in Java
但是简短的描述是:
如果存在另一个名称更接近范围的变量,则该变量将被覆盖
一个显示此阴影的小例子是
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"
}
}