列表框可以同时将多个选项信息以列表的方式展现给用户,使用JList可以构建一个列表框。
package com.beyole.util; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.ListSelectionModel; class MyList { private JFrame frame = new JFrame("Beyole"); private Container container = frame.getContentPane(); private JList list1 = null;// 定义列表框 private JList list2 = null;// 定义列表框 public MyList() { this.frame.setLayout(new GridLayout(1, 2)); String nation[] = { "中国", "日本", "俄罗斯", "朝鲜", "美国" }; Vector<String> vector = new Vector<String>(); vector.add("主站"); vector.add("博客"); vector.add("论坛"); this.list1 = new JList(nation); this.list2 = new JList(vector); list1.setBorder(BorderFactory.createTitledBorder("你喜欢哪个国家")); list2.setBorder(BorderFactory.createTitledBorder("你喜欢哪个网站")); list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); container.add(this.list1); container.add(this.list2); this.frame.setSize(330, 180); this.frame.setVisible(true); this.frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent arg0) { System.exit(1); } }); } } public class JListDemo01 { public static void main(String[] args) { new MyList(); } }
以上程序中第一个JList通过字符串数组设置列表的内容,并通过setSelectionMode()方法设置一次性可以选择的一个选项,第二个JList通过Vector设置列表的内容,并通过setSelectionMode()方法设置一次性可以选择的多个选项
程序截图: