我试图从dificultad
方法中的变量actionPerformed
获取值,以便在另一个类中使用它。但我真的不知道如何做到这一点。所以我不知道你是否可以提供帮助。
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");
}
}
答案 0 :(得分:1)
在班级顶部定义一个变量(public)。
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;
}
}
}
}
要在其他类中使用该值,只需传递类对象 - 例如 - 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!");
}
}
}
希望这有帮助。
答案 1 :(得分:0)
//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;
}