package org.haha;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/**
* 小应用程序有两个列表,第一个列表只允许单选,第二个列表允许多选
* @author admin
*
*/
public class JListTest extends JFrame implements ListSelectionListener{
public static void main(String[] args) {
new JListTest("列表示例");
}
JList list1,list2;
JTextArea text;
String news[] = {"人民日报","新民晚报","浙江日报","文汇报"};
String sports[] = {"足球","乒乓球","篮球","排球"};
JListTest(String s){
super(s);
Container con = this.getContentPane();
//con.setBackground(Color.BLUE);
con.setLayout(new GridLayout(2,2));
con.setSize(200, 500);
list1 = new JList(news);
list1.setVisibleRowCount(3);
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);//单选
list1.addListSelectionListener(this);//注册监视器
list2 = new JList(sports);
list2.setVisibleRowCount(2);
list2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);//多选
list2.addListSelectionListener(this);
con.add(list1); con.add(list2);
text = new JTextArea(10,20);
con.add(text);
this.setVisible(true); this.pack();
}
public void valueChanged(ListSelectionEvent e) {
if(e.getSource()==list1){
text.setText(null);
Object listValue = ((JList)e.getSource()).getSelectedValue();//获取选项的值
String selectName = listValue.toString();
for(int i=0;i
if(news[i].equals(selectName)){
text.append(selectName+":被选中\n");
}
}
}
if(e.getSource()==list2){
text.setText(null);
int[] list = ((JList)e.getSource()).getSelectedIndices();//返回所选的全部索引的数组(按升序排列)。
for(int i=0;i
text.append(sports[list[i]]+":被选中\n");
}
}
}
}