问答题

本程序的功能是监听列表的选择,并将选中的内容显示在文本域中。窗口中有一个文本域和一个支持多项选择的列表,当选中列表中的一项或多项时,文本域中就会分行显示所选项的索引值和值,如图所示。


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class exam_37
{
public static void main (String[] args)
{
ListFrame frame=new ListFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class ListFrame extends JFrame
{
public ListFrame()
{
setTitle("exam_37");
setSize(WIDTH, HEIGHT);
Container contentPane=getContentPane();
JPanel textPanel=new JPanel();
myTextArea=new JTextArea(checkedLabel, 5, 20);
JScrollPane textScrollPane=new JScrollPane(myTextArea);
textPanel.add(textScroilPane);
contentPane.add(textPanel);
listPanel=new JPanel();
String[] courses={"数学", "英语", "物理", "化学", "生物", "地理"};
courseList=new JList(courses);
courseList.setVisibleRowCount(4);
courseList.addListSelectionListener(new courseListener());
JScrollPane listScrollPane=new JScrollPane(courseList);
listPanel.add(listScrollPane);
contentPane.add(listPanel, BorderLayout.SOUTH);
private class courseListener implements ListSelectionListener
public void valueChanged(ListSelectionEvent event)
{
Object[] selectedCourses=courseList.getSelectedValues();
int[] selectedIndexCourses=courseList.getSelectedIndices();
StringBuffer tempSeletedText=new StringBuffer(checkedLabel);
for (int i=0; ______; i++)
{
String strl=new String(selectedIndexCourses[i] + ", ");
String str2=(String) selectedCourses[i];
tempSeletedText.append(str1);
tempSeletedText.append(str2);
tempSeletedText.append("\n");
}
myTextArea.setText(______);
}
}
public static final int WIDTH=300;
public static final int HEIGHT=250;
public static final String checkedLabel="请选择你喜欢的课程:\n";
private JTextArea myTextArea;
private JList courseList;
private JPanel listPanel;
}

【参考答案】

第1处:i < selectedCourses.length
第2处:tempSeletedText.toString()
热门 试题