This article is your own study notes, welcome reprint, but please indicate the source: http://blog.csdn.net/jesson20121020
The list box and the JComboBox combo box are significantly different, not just in appearance. When the JComboBox combo box is activated, a drop-down list appears, and JList always occupies a fixed line of space on the screen, and the size does not change. If you want to get the selected item in the list box, just call Getselectvalues (), which can produce an array of strings with the selected item name.
In addition, the JList component also allows multiple selections, and if you hold down the CTRL key and click on multiple items consecutively, the previously selected item remains selected, that is, you can select as many items as you like, and if you select an item, Shift-click another item, Then all items between these two items will be selected, which is similar to the actions selected under Windows.
public class List extends JFrame {private string[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};p rivate Defaultlistmodel litems = new Defaultlistmodel ();p rivate JList lst = new JList (litems);p rivate jtextarea t = new JTextArea (weekdays.length,10);p rivate JButton b = new JButton ("Add Items");p rivate int count = 0;private ActionListener bl = new Ac Tionlistener () {@Overridepublic void actionperformed (ActionEvent e) {//TODO auto-generated method Stubif (Count < week Days.length) {litems.add (0, weekdays[count++]);} Else{b.setenabled (FALSE);}}; Private Listselectionlistener LL = new Listselectionlistener () {@Overridepublic void valuechanged (Listselectionevent e) {//TODO auto-generated method Stubif (e.getvalueisadjusting ()) return; T.settext (""); for (Object item: Lst.getselectedvalues ()) T.append (item + "\ n");}; Public List () {//TODO auto-generated constructor Stubsetlayout (new FlowLayout ()); setvisible (true); SetSize (300,200); T.setenabled (FALSE); Border BRD = Borderfactory.creatematteBorder (1, 1, 2, 2, Color.Black); Lst.setborder (BRD); T.setborder (BRD); for (int i = 0; i < 4;i++) {litems.addelement ( weekdays[count++]);} Add (t); add (LST); add (b); Lst.addlistselectionlistener (ll); B.addactionlistener (BL);} /** * @param args */public static void main (string[] args) {//TODO auto-generated method Stubnew List ();}}
The results of the implementation are as follows:
in fact, in many applications can see this list box, in addition, when the list box too many items, JList does not provide scrolling, of course, you can wrap the jlist to JScrollPane, then it will achieve scrolling effect.
Java Interface Programming (9)------list box