Java Swing中JList选择事件监听器ListSelectionListener用法示例

时间:2022-09-18 11:08:38

本文实例讲述了java swing中jlist选择事件监听器listselectionlistener用法。分享给大家供大家参考,具体如下:

当jlist中的元素被选中时,选择事件将被触发。对于jtable也是一样,你可以把它看做是多个并列的jlist。那么,如果程序需要对该事件做出响应,需要以下步骤:

(1)创建一个实现了 listselectionlistener的监听器;
(2)使用jlist或selectionmodel的addlistselectionlistener添加监听器;
(3)在监听器的valuechanged方法添加响应代码。

在响应代码中需要注意的是getvalueisadjusting值的判断。测试表明,每当我们进行选择时,valuechanged方法都会被激活多次,其中,在最后的鼠标操作中,getvalueisadjusting值为false,而在一系列中间操作中,该值均为true。比如说,用鼠标连续划过一串元素时,会有一系列getvalueisadjusting为true的valuechanged方法激活,且最后一次为false。而我们对选择事件的判定一般是以最后接触为准,因此这里对getvalueisadjusting值进行一个判断。

常用方法如下:

getleadselectionindex()
返回当前选中的元素的index。

getminselectionindex()
返回选中的多个元素中index的最小值,如果选择为空在返回-1。

getmaxselectionindex()
原理同上。

isselectedindex(int index)
判断指定index是否被选中。

clearselection()
清除选中。

getselectedindex()
返回被选中的所有元素中最小的index。

getselectedindices()
返回一个整型数组,包含被选中的所有index。

getselectedvalue()
返回被选中的,index最小的元素值。

getselectedvalues()
返回一个object数组,包含被选中的所有元素对象。

getselectedvalueslist()
返回一个objectlist,包含被选中的所有元素对象。

下面的demo来自于listselectiondemo.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
/*
 * copyright (c) 1995, 2008, oracle and/or its affiliates. all rights reserved.
 *
 * redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  - redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 *  - redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 *  - neither the name of oracle or the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * this software is provided by the copyright holders and contributors "as
 * is" and any express or implied warranties, including, but not limited to,
 * the implied warranties of merchantability and fitness for a particular
 * purpose are disclaimed. in no event shall the copyright owner or
 * contributors be liable for any direct, indirect, incidental, special,
 * exemplary, or consequential damages (including, but not limited to,
 * procurement of substitute goods or services; loss of use, data, or
 * profits; or business interruption) however caused and on any theory of
 * liability, whether in contract, strict liability, or tort (including
 * negligence or otherwise) arising in any way out of the use of this
 * software, even if advised of the possibility of such damage.
 */
package awtdemo;
/*
 * listselectiondemo.java requires no other files.
 */
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
@suppresswarnings("serial")
public class listselectiondemo extends jpanel {
  jtextarea output;
  @suppresswarnings("rawtypes")
 jlist list;
  jtable table;
  string newline = "\n";
  listselectionmodel listselectionmodel;
  @suppresswarnings({ "unchecked", "rawtypes" })
 public listselectiondemo() {
    super(new borderlayout());
    string[] listdata = { "one", "two", "three", "four",
               "five", "six", "seven" };
    @suppresswarnings("unused")
 string[] columnnames = { "french", "spanish", "italian" };
    list = new jlist(listdata);
    listselectionmodel = list.getselectionmodel();
    listselectionmodel.addlistselectionlistener(
        new sharedlistselectionhandler());
    jscrollpane listpane = new jscrollpane(list);
    jpanel controlpane = new jpanel();
    string[] modes = { "single_selection",
              "single_interval_selection",
              "multiple_interval_selection" };
    final jcombobox combobox = new jcombobox(modes);
    combobox.setselectedindex(2);
    combobox.addactionlistener(new actionlistener() {
      public void actionperformed(actionevent e) {
        string newmode = (string)combobox.getselecteditem();
        if (newmode.equals("single_selection")) {
          listselectionmodel.setselectionmode(
            listselectionmodel.single_selection);
        } else if (newmode.equals("single_interval_selection")) {
          listselectionmodel.setselectionmode(
            listselectionmodel.single_interval_selection);
        } else {
          listselectionmodel.setselectionmode(
            listselectionmodel.multiple_interval_selection);
        }
        output.append("----------"
               + "mode: " + newmode
               + "----------" + newline);
      }
    });
    controlpane.add(new jlabel("selection mode:"));
    controlpane.add(combobox);
    //build output area.
    output = new jtextarea(1, 10);
    output.seteditable(false);
    jscrollpane outputpane = new jscrollpane(output,
             scrollpaneconstants.vertical_scrollbar_always,
             scrollpaneconstants.horizontal_scrollbar_as_needed);
    //do the layout.
    jsplitpane splitpane = new jsplitpane(jsplitpane.vertical_split);
    add(splitpane, borderlayout.center);
    jpanel tophalf = new jpanel();
    tophalf.setlayout(new boxlayout(tophalf, boxlayout.line_axis));
    jpanel listcontainer = new jpanel(new gridlayout(1,1));
    listcontainer.setborder(borderfactory.createtitledborder(
                        "list"));
    listcontainer.add(listpane);
  tophalf.setborder(borderfactory.createemptyborder(5,5,0,5));
    tophalf.add(listcontainer);
    //tophalf.add(tablecontainer);
    tophalf.setminimumsize(new dimension(100, 50));
    tophalf.setpreferredsize(new dimension(100, 110));
    splitpane.add(tophalf);
    jpanel bottomhalf = new jpanel(new borderlayout());
    bottomhalf.add(controlpane, borderlayout.page_start);
    bottomhalf.add(outputpane, borderlayout.center);
    //xxx: next line needed if bottomhalf is a scroll pane:
    //bottomhalf.setminimumsize(new dimension(400, 50));
    bottomhalf.setpreferredsize(new dimension(450, 135));
    splitpane.add(bottomhalf);
  }
  /**
   * create the gui and show it. for thread safety,
   * this method should be invoked from the
   * event-dispatching thread.
   */
  private static void createandshowgui() {
    //create and set up the window.
    jframe frame = new jframe("listselectiondemo - www.zzvips.com");
    frame.setdefaultcloseoperation(jframe.exit_on_close);
    //create and set up the content pane.
    listselectiondemo demo = new listselectiondemo();
    demo.setopaque(true);
    frame.setcontentpane(demo);
    //display the window.
    frame.pack();
    frame.setvisible(true);
  }
  public static void main(string[] args) {
    //schedule a job for the event-dispatching thread:
    //creating and showing this application's gui.
    javax.swing.swingutilities.invokelater(new runnable() {
      public void run() {
        createandshowgui();
      }
    });
  }
  class sharedlistselectionhandler implements listselectionlistener {
    public void valuechanged(listselectionevent e) {
      listselectionmodel lsm = (listselectionmodel)e.getsource();
      //system.out.printf("leadselectionindex is %s%n",lsm.getleadselectionindex());
      output.append("leadselectionindex is " + lsm.getleadselectionindex() + "\n");
      int firstindex = e.getfirstindex();
      int lastindex = e.getlastindex();
      boolean isadjusting = e.getvalueisadjusting();
      output.append("event for indexes "
             + firstindex + " - " + lastindex
             + "; isadjusting is " + isadjusting
             + "; selected indexes:");
      if (lsm.isselectionempty()) {
        output.append(" <none>");
      } else {
        // find out which indexes are selected.
        int minindex = lsm.getminselectionindex();
        int maxindex = lsm.getmaxselectionindex();
        for (int i = minindex; i <= maxindex; i++) {
          if (lsm.isselectedindex(i)) {
            output.append(" " + i);
          }
        }
      }
      output.append(newline);
      output.setcaretposition(output.getdocument().getlength());
    }
  }
}

运行效果:

Java Swing中JList选择事件监听器ListSelectionListener用法示例

希望本文所述对大家java程序设计有所帮助。

原文链接:http://www.cnblogs.com/pzy4447/p/4912584.html