我正在读取一个名为: class_list和class_list.isSelectedIndex(N)的选项;其中n=0,1,2,3,4和当我执行代码并从JList中选择任何选项时,我得到相同的输出,当n==1和n==4时,我总是得到Joption和"Anita sharma“作为输出。
这是我的代码
for (int n = 0; n <= 4; n++) { // n is index value from 0-4
class_list.isSelectedIndex(n);
if (n == 0) {
JOptionPane.showMessageDialog(this,
"Choose Any Class to Know the name of \n their Resppective Class Teacher");
}
if (n == 1) {
show_name.setText("Purnima Singh");
} // if n=1 1st list selected
if (n == 2) {
show_name.setText("Suruchi Oberoi");
}
if (n == 3) {
show_name.setText("Manjula");
}
if (n == 4) {
show_name.setText("Anita Misra");
}
}发布于 2014-02-13 14:30:43
您的代码运行良好。使用您的代码,for循环将遍历0-4并相应地更改文本。然而,只有最后一次(i==4)执行是可见的,因为它的下一次迭代覆盖了之前的更改。
下面是与上面的for循环对应的有效代码:
show_name.setText("Anita Misra");发布于 2014-02-13 20:01:26
这是一个非常低效的代码,不需要任何循环。试试这个:
private void class_listMouseClicked(java.awt.event.MouseEvent evt) {
String[] teachers={"Purnima Singh","Suruchi Oberoi","Manjula","Anita Misra"};
int selection=class_list.getSelectedIndex();
if(selection>0&&selection<=4) { show_name.setText(teachers[selection-1]); }
else {
JOptionPane.showMessageDialog(null, "Choose Any Class to Know the name of \n their Respective Class Teacher");
}
}以下是操作http://s29.postimg.org/vwl72sv0l/Untitled.jpg中的代码的屏幕截图
解释:每当用户单击list时,我们都会将代码添加到MouseClicked操作中,class_list.getSelectedIndex()将获得所选元素的索引。记住,索引是从零开始的,但是在我们的列表中,第一个元素是标题"Class Name“,所以我们从selection变量中减去1。任务完成了就是这样。
如果您有疑问,请参考javadoc。
您的代码已更正:
int selection=0;
for (int n = 0; n <= 4; n++) { // n is index value from 0-4
if(class_list.isSelectedIndex(n)==true) { selection=n; }
}
if (selection == 0) {
JOptionPane.showMessageDialog(this,
"Choose Any Class to Know the name of \n their Resppective Class Teacher");
}
if (selection == 1) {
show_name.setText("Purnima Singh");
} // if n=1 1st list selected
if (selection == 2) {
show_name.setText("Suruchi Oberoi");
}
if (selection == 3) {
show_name.setText("Manjula");
}
if (selection == 4) {
show_name.setText("Anita Misra");
}发布于 2014-02-13 20:12:18
您还可以使用如下代码:在任何情况下,您都可以在此方法中添加任何大小写:
switch (n) {
case 0: JOptionPane.showMessageDialog(this,
"Choose Any Class to Know the name of \n their Resppective Class Teacher");
break;
case 1:
show_name.setText("Purnima Singh");
break;
case 2:
show_name.setText("Suruchi Oberoi");
break;
case 3:
show_name.setText("Manjula");
break;
case 4:
show_name.setText("Anita Misra");
break;
}如果要对n的许多值执行相同的操作,则可以更改结构,如下所示:
case 0:
case 5: Do your operation for `0` and `5` cases; break;https://stackoverflow.com/questions/21746715
复制相似问题