Java Interface Programming (9), java Interface Programming
This article is my learning notes, welcome to reprint, but please note the Source: http://blog.csdn.net/jesson20121020
The list box and the JComboBox combo box are obviously different. This is not only reflected in the appearance. When the JComboBox combo box is activated, a drop-down list is displayed. The JList always occupies the space of fixed Rows on the screen, and the size does not change. To obtain the selected project in the list box, you only need to call getSelectValues () to generate a string array containing the selected project name.
In addition, the JList component allows multiple selections. If you press and hold the ctrl key and click multiple items consecutively, the selected items remain in the selected status, that is to say, you can select any number of projects. If you select a project, press shift and click another project, all the projects between the two projects will be selected, this is similar to the selected operation in windows.
Public class List extends JFrame {private String [] weekDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Saturday ", "Sunday"}; private defalistlistmodel lItems = new DefaultListModel (); private JList lst = new JList (lItems); private JTextArea t = new JTextArea (weekDays. length, 10); private JButton B = new JButton ("Add Items"); private int count = 0; private ActionListener bl = new ActionListener () {@ Overridepublic void actionreceivmed (ActionEvent e) {// TODO Auto-generated method stubif (count <weekDays. 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 execution result is as follows:
In fact, this list box can be seen in many applications. In addition, when there are too many items in the list box, JList does not provide scrolling. Of course, JList can be packaged into JScrollPane, then it will implement the rolling effect.