package swing; import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.event.*; public class sandemo extends JFrame{ JList list1,list2; Container container; sandemo(){ container=this.getContentPane(); list1=new JList(); String []str= {"li se","hh kjk","hf us","hf au","uh ue"}; list1.setListData(str); list1.setSelectionForeground(Color.red);//把选择的数据信息颜色变为红色 list2=new JList(); JScrollPane jsp1=new JScrollPane(list1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); JScrollPane jsp2=new JScrollPane(list2,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); JPanel p=new JPanel(); p.add(jsp1); p.add(jsp2); container.add(p); list1.addListSelectionListener(new ListSelectionListener() {//注册事件监听程序 匿名类 public void valueChanged(ListSelectionEvent e) { Object []str=list1.getSelectedValues();//获取选择内容 list2.setListData(str); } }); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); this.setTitle("列表框练习"); this.setSize(600,450); this.setVisible(true); } public static void main(String []args) { new sandemo(); } }
运行结果为: