Java JList 元素上的双击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4344682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:15:02  来源:igfitidea点击:

Double-click event on JList element

javaswingjlistdefaultlistmodel

提问by Lobo

I have a JListwith a DefaultListModel.

我有JList一个DefaultListModel.

How I can make an item in a JListreact to double-click event?

如何使项目JList对双击事件做出反应?

采纳答案by Mohamed Saligh

String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);

list.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent evt) {
        JList list = (JList)evt.getSource();
        if (evt.getClickCount() == 2) {

            // Double-click detected
            int index = list.locationToIndex(evt.getPoint());
        } else if (evt.getClickCount() == 3) {

            // Triple-click detected
            int index = list.locationToIndex(evt.getPoint());
        }
    }
});

回答by camickr

I know you have a simple solution, but you may want to check out List Actionfor a more general solution that will allow you to use the mouse as well as the key board. Proper GUI design should allow the use to use either approach.

我知道您有一个简单的解决方案,但您可能想查看List Action以获得更通用的解决方案,该解决方案将允许您使用鼠标和键盘。正确的 GUI 设计应该允许使用任何一种方法。

回答by SandroMarques

(based on Mohamed Saligh, the accepted response)

(基于 Mohamed Saligh,已接受的回复)

If you are using NetBeans

如果您使用的是 NetBeans

Select the JList > Events window > mouseClicked

选择 JList > 事件窗口 > mouseClicked

private void jListNicknamesMouseClicked(java.awt.event.MouseEvent evt) {                                            
    JList list = (JList)evt.getSource();
    if (evt.getClickCount() == 2) {
        int index = list.locationToIndex(evt.getPoint());
        System.out.println("index: "+index);
    }
}