有人知道我如何在 Action 监听器中执行此操作吗?我有以下内容
private void (java.awt.event.ItemEvent evt) {
if (studentComboBox.getSelectedItem().equals("Student 1")){
jlabel1=return parameter ="i"
String i = getParameter("student2");
但我确定返回参数不正确
最佳答案
Return 允许您指定要返回的值。它不允许你做作业;由调用您的方法的代码来确定如何操作。
无论如何,您的方法 studentComboBoxItemStateChanged
是一个 void
方法,这意味着它无法返回值(常规 return
有效,它只是留下方法)。
这取决于您和您的需要。针对您的情况,最好的解决方案可能是在每个 if
中设置一些变量或使用参数调用一些函数。
编辑如果您尝试将 jlabel1 的值设置为 "h"
、"i"
、"j “
if (studentComboBox.getSelectedItem().equals("Student 1")) { jlabel1.setValue("h"); }
....
但看起来您正在尝试使用变量 h
、i
和 j
。请记住,"h"
与 h
不同。
if (studentComboBox.getSelectedItem().equals("Student 1")) { jlabel1.setValue(h); }
....
但要做到这一点,h
、i
和 j
需要在方法外部定义为实例变量。
在这种情况下,假设标签应保存 getParameter("student1") 的值,最好的解决方案就是这样做:
if (studentComboBox.getSelectedItem().equals("Student 1")) { jlabel1.setValue(getParameter("student1")); }
....
正如其他人提到的, map 非常适合此目的
Map<String, String> prettyNamesToParameterNames= ...;
private void StudentComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {
String paramName=prettyNamestoParameterNames.get(studentComboBox.getSelectedItem());
label1.setValue(getParameter(paramName));
}
关于java - 在小程序中返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390841/