Usage example of JList selection event listener listselectionlistener in Java Swing
This article describes the usage of JList selection event listener listselectionlistener in Java swing. Share with you for your reference, as follows:
When the element in JList is selected, the selection event will be triggered. The same is true for JTable. You can think of it as multiple parallel jlists. Then, if the program needs to respond to this event, the following steps are required:
(1) Create a listener that implements listselectionlistener; (2) Add listeners using addlistselectionlistener of JList or selectionmodel; (3) Add the response code in the valuechanged method of the listener.
In the response code, you should pay attention to the judgment of getvalueisadjusting value. The test shows that whenever we make a selection, the valuechanged method will be activated multiple times. In the last mouse operation, the getvalueisadjusting value is false, while in a series of intermediate operations, the value is true. For example, when the mouse continuously crosses a string of elements, a series of valuechanged methods with getvalueisadjusting true will be activated, and the last time is false. Our judgment on the selection event is generally based on the last contact, so here we judge the getvalueisadjusting value.
Common methods are as follows:
Getleadselectionindex() returns the index of the currently selected element.
Getminselectionindex() returns the minimum value of index among the selected elements. If the selection is empty, it returns - 1.
The principle of getmaxselectionindex() is the same as above.
Isselectedindex (int index) determines whether the specified index is selected.
Clearselection() clears the selection.
Getselectedindex() returns the smallest index of all selected elements.
Getselectedindices() returns an integer array containing all the indexes selected.
Getselectedvalue() returns the smallest element value of the selected index.
Getselectedvalues () returns an object array containing all the selected element objects.
Getselectedvalueslist() returns an objectlist containing all the selected element objects.
The following demo is from listselectiondemo java
Operation effect:
More readers interested in Java related content can view the special topics of this site: Java data structure and algorithm tutorial, summary of Java character and string operation skills, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills