我有一台带DefaultListModel
的JList
。
如何使JList
中的项对双击事件做出反应?
发布于 2010-12-03 18:45:14
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());
}
}
});
发布于 2015-03-18 16:28:07
(基于穆罕默德·萨利,接受的回复)
如果您正在使用NetBeans
选择“JList”>“Events”窗口>“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);
}
}
发布于 2010-12-04 00:34:51
我知道您有一个简单的解决方案,但您可能想要查看List Action,以获得一个更通用的解决方案,它将允许您使用鼠标和键盘。正确的GUI设计应该允许用户使用这两种方法中的任何一种。
使用ListAction
的最基本示例是:
String[] data = { "zero", "one", "two", "three", "four", "five" };
JList list = new JList( data );
Action displayAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
JList list = (JList)e.getSource();
System.out.println(list.getSelectedValue());
}
};
ListAction la = new ListAction(list, displayAction);
https://stackoverflow.com/questions/4344682
复制相似问题