List boxes are generated by the Swing component JList, which always occupies a fixed number of rows on the screen. If you want to get the selected element in the list box, just call getSelectedValuesList(), which can produce an array of strings with the selected element name. The JList component allows multiple selections; if you hold down the Ctrl key, you can select all clicked elements; if you select an element, hold down the Shift key and click another element, then all elements between the two elements are selected; to remove one from the selected element, hold down the Ctrl key and click the element.
After initializing the list box, then adding and modifying content to the list box. It is divided into static operations and dynamic operations.
1. Static operation
Static operation means adding all elements to JList at the same time. After adding, it cannot be modified or deleted. That is, the list box cannot be operated during the program execution.
Eg
package test;import javax.swing.*;import java.awt.*;import static net.mindview.util.SwingConsole.*;public class ListTest1 extends JFrame{private String[] str = {"Monday","Tuesday","Wednesday","Thursday","Friday","Staturday","Sunday"};private JList list;public ListTest1(){list = new JList(str);setLayout(new FlowLayout());add(list);}public static void main(String[] args){run(new ListTest1(),200,100);}}As in the above example, just add all elements when initializing JList.
Execution result: The list box cannot be operated.
2. Dynamic operation
By looking at the JList method, you can find that JList is not responsible for the dynamic operation of the list box. All the details of the dynamic operation can be completed in the "list model", namely the DefaultListModel. Just add the list model to the JList.
DefaultListModel listmodel = new DefaultListModel();listmodel.addElement(element1);//Add element listmodel.clear();//Clear all elements listmodel.remove(int index);//Clear elements at the specified position
Eg
package test;import java.awt.*;import java.awt.event.*;import static net.mindview.util.SwingConsole.*;import javax.swing.border.Border;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;public class ListTest extends JFrame{private String[] str = {"Monday","Tuesday","Wednesday","Thursday","Friday","Staturday","Sunday"};private JButton button1 = new JButton("Add Item"),button2 = new JButton("Clear Item");private JTextArea text = new JTextArea(str.length,20);private DefaultListModel listmodel = new DefaultListModel();private JList list = new JList(listmodel);//Add the list model to JList, the list model is responsible for completing dynamic operations, and JList is responsible for creating lists and many other tasks (such as multiple selection). private int count = 0;private boolean flag = false;public ListTest(){text.setEditable(false);//It is only used to display, and cannot be edited for(int i = 0;i<4;i++){listmodel.addElement(str[count++]);} button1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if(count<str.length){listmodel.addElement(str[count++]);}else{button1.setEnabled(flag);flag = true;}}});button2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if(count<str.length){count = 0;//Restart the listmodel.clear();//Click the list element text.setText(null);}else{count = 0;listmodel.clear();text.setText(null);button1.setEnabled(flag);//Start button}}});list.addListSelectionListener(new ListSelectionListener(){@SuppressWarnings("deprecation")public void valueChanged(ListSelectionEvent e){if(e.getValueIsAdjusting())return;//If the event is detected to be changing, it returns true, and the subsequent statement will not be executed; when the change is finished, it returns false and the subsequent statement will be executed. for(Object item: list.getSelectedValuesList()){text.append(item + "/n");//Convert a List object to Object}//list calls the getSelectedValuesList() method to generate an array of strings with the selected element name}});setLayout(new FlowLayout());Border border = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.RED);//Add border list.setBorder(border);//Set border text.setBorder(border);add(button1);add(button2);add(new JScrollPane(text));add(list);}public static void main(String[] args) {run(new ListTest(),250,375);}}Execution results:
In the above program, the getValueIsAdjusting() method of the event ListSelectionEvent supported by JList and the getSelectedValuesList() method of JList are used in the processing process of JList. Pay attention to the usage of these two methods.
(1)Boolean javax.swing.event.ListSelectionEvent.getValueIsAdjusting()
Returns whether this event is one of multiple different events that are still changing, and returns true if this event is one of multiple different events that are still changing.
For example, for an event that selects to be updated in response to a user's drag, this property is set to true at the start of the drag; and is set to false at the end of the drag. During dragging, the listener receives an event where the valueIsAdjusting property is set to true. At the end of the drag, when the change terminates, the listener receives an event with a value set to false.
If you remove the update detection statement from the registration program of the JList object:
if(e.getValueIsAdjusting()) return;
The output is:
It can be seen that there is no update detection, and after selecting the list box element, there is repeated output.
(2)List javax.swing.JList.getSelectedValuesList()
The JList object calls the getSelectedValuesList() method to generate an array of strings with the selected element name.
3. JList scrollbar
JList does not provide direct support for scrolling, we just wrap JList into JScrollPane, it will automatically help with all the details.
Summary: If you want to add elements to JList, you can perform static operations that add all elements when JList is initialized, or you can use the "List Model" DefaultListModel to process dynamic operations of all list modification details.
Note: Update detection may be used during the selection of JList elements to ensure the stability of the program.
The above is the list box of the java graphical user interface introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!