当前位置: 移动技术网 > IT编程>开发语言>Java > Java Swing中JList选择事件监听器ListSelectionListener用法示例

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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

/*
 * 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.jb51.net");
    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相关内容感兴趣的读者可查看本站专题:《java数据结构与算法教程》、《java字符与字符串操作技巧总结》、《java操作dom节点技巧总结》、《java文件与目录操作技巧汇总》和《java缓存操作技巧汇总

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网