Java Swing中JList选择事件 * ListSelectionListener用法示例
作者:pzy4447 发布时间:2021-06-21 22:52:01
本文实例讲述了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程序设计有所帮助。
来源:http://www.cnblogs.com/pzy4447/p/4912584.html


猜你喜欢
- 前提说明之前公司有一个项目是由androidstudio接入高德地图实现导航,定位等功能,然后还有一部分登陆页面和其他逻辑都放在Unity方
- Java怎么自动添加重写的toString方法,这里我们将给大家介绍详细的解决方法。首先,添加一个任意的类,具体的类型没有要求,然后在主程序
- 前言2016年3月修改,结合自己的工作和平时学习的体验重新谈一下为什么要进行代码优化。在修改之前,我的说法是这样的:就像鲸鱼吃虾米一样,也许
- <results>标签在Struts2的MVC框架的视图中所扮演的角色。动作是负责执行业务逻辑。执行业务逻辑后,接下来的步骤是使
- 1) 要及时回收Bitmap的内存Bitmap类有一个方法recycle(),从方法名可以看出意思是回收。这里就有疑问了,Android系统
- 在web页面上我们可以通过frameset,iframe嵌套框架很容易实现各种导航+内容的布局界面,而在winform、WPF中实现其实也很
- feign对象传参和普通传参及遇到的坑对象传参使用@RequestBody来指定传参对象@RequestMapping(value = &q
- Dubbo服务暴露机制前言在进行服务暴露机制的分析之前,必须谈谈什么是URL,在Dubbo服务暴露过程中URL是无处不在的,贯穿了整个过程。
- Android9.0无法通过以下两种方式实现静默安装:1.runtime执行shell cmd2.PackageInstall 反射机制但是
- FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写FreeMarker被设计用来生成HTML Web
- 1、比较器①比较器的引入a.首先,当我们单一地比较某一种数据类型的数组时,可以直接用Arrays.sort()进行实现b.而当我们同时含有多
- 之前我们借助一个SuperSocket实现了一个简易版的服务器, 但是不管是Server还是Session都是使用框架的,本篇博客我们要实现
- 在工作上,我最近对一个现有的Java项目代码进行了清理。完成之后,我发现了一些反复出现的不规范代码。所以,我把它们整理成了一个列表出来分享给
- 本文实例讲述了Android TextView实现带链接文字事件监听的三种常用方式。分享给大家供大家参考,具体如下:/** * TextVi
- 原始数据:string input = "3,7,2,8,1,9,1,34,67,78,22";要处理为:string[
- Mybatis获取参数值的两种方式:${},#{}${}本质:字符串拼接,注意:单引号要加上#{}:本质:占位符赋值一、 Mybatis获取
- 获取map的值主要有四种方法,这四种方法又分为两类,一类是调用map.keySet()方法来获取key和value的值,另一类则是通过map
- Activity栈主要用于管理Activity的切换。当使用Intent跳转至某个目标Activity,需要根据目标Activity的加载模
- 本文实例为大家分享了TabLayout结合ViewPager实现页面切换效果的具体代码,供大家参考,具体内容如下先看看效果,如图:1.因为T
- 前言本文基于itext7实现pdf加水印和合并的操作。实际上在我们实际项目应用中,对于pdf的操作也是比较常见的,我上一个项目中就有将结果转