[英]Selecting a value from an actionPerformed method
I'm trying to get the value from the variable dificultad
, which is inside the actionPerformed
method to use it in another class. 我试图从变量
dificultad
获取值,该变量在actionPerformed
方法内部,以便在另一个类中使用它。 But I really have no clue on how to do it. 但是我真的不知道该怎么做。 So I don't know if maybe you could help.
因此,我不知道您是否可以提供帮助。
jComboBox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int dificultad;
if (jComboBox1.getSelectedItem() == "Facil") {
dificultad = 10;
System.out.println("Facil");
} else if (jComboBox1.getSelectedItem() == "Intermedio") {
dificultad = 8;
System.out.println("Intermedio");
} else if (jComboBox1.getSelectedItem() == "Dificil") {
dificultad = 4;
System.out.println("Dificl");
} else if (jComboBox1.getSelectedItem() == "Extremo") {
dificultad = 1;
System.out.println("Extremo");
}
}
Define a variable (public) at the top of your class. 在类的顶部定义一个变量(公共)。
public class testClass {
public int testVar = 0;
public void action(){
jComboBox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int dificultad;
if (jComboBox1.getSelectedItem() == "Facil") {
dificultad = 10;
System.out.println("Facil");
} else if (jComboBox1.getSelectedItem() == "Intermedio") {
dificultad = 8;
System.out.println("Intermedio");
} else if (jComboBox1.getSelectedItem() == "Dificil") {
dificultad = 4;
System.out.println("Dificl");
} else if (jComboBox1.getSelectedItem() == "Extremo") {
dificultad = 1;
System.out.println("Extremo");
}
testVar = dificultad;
}
}
}
}
To use the value in an other class, simply pass the class object in - for example - a main
function and access to the variable. 要在其他类中使用该值,只需在(例如)
main
函数中传递类对象并访问变量即可。
public class testClass2 {
public testClass;
public testClass2(testClass tc) {
this.testClass = tc;
}
public void anotherAction(){
if (this.testClass.testVar == 1) {
System.out.println("Extremo!");
}
}
}
Hope this helps. 希望这可以帮助。
//set a field to use outside the scope of addActionListener()
int laDificulty = 0;
jComboBox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int dificultad;
if (jComboBox1.getSelectedItem() == "Facil") {
dificultad = 10;
System.out.println("Facil");
} else if (jComboBox1.getSelectedItem() == "Intermedio") {
dificultad = 8;
System.out.println("Intermedio");
} else if (jComboBox1.getSelectedItem() == "Dificil") {
dificultad = 4;
System.out.println("Dificl");
} else if (jComboBox1.getSelectedItem() == "Extremo") {
dificultad = 1;
System.out.println("Extremo");
}
laDificulty = dificultad;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.