我有简单的代码示例。如何添加鼠标侦听器以显示所选JList项目的简单菜单(当我单击鼠标右键时)?另外:如何为鼠标左键添加鼠标监听器?
像这样:
这是我的代码:
package test;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class Test implements ActionListener {
private JList list;
private MyJListModel model;
public Test() {
JFrame frame = new JFrame("Test");
frame.setMinimumSize(new Dimension(400,200));
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenuItem addItem = new JMenuItem("Add");
filemenu.add(addItem);
menubar.add(filemenu);
addItem.addActionListener(this);
model = new MyJListModel();
list = new JList(model);
JScrollPane scrollpane = new JScrollPane(list);
frame.add(scrollpane);
frame.setJMenuBar(menubar);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String pushedItem = event.getActionCommand();
if(pushedItem.equals("Add")) {
model.addElement("Item");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
}
class MyJListModel extends AbstractListModel {
private ArrayList<String> arraylist = new ArrayList<String>();
public MyJListModel() {
super();
}
@Override
public int getSize() {
return arraylist.size();
}
@Override
public Object getElementAt(int i) {
return arraylist.get(i);
}
public void addElement(String string) {
arraylist.add(string);
this.fireContentsChanged(this, 0, arraylist.size() - 1);
}
}
答案 0 :(得分:2)
将mouselistener添加到表中,而不是模型。
Table.addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
if(e.isPopupTrigger())
{
onShowPopup(e);
}
}
public void mousePressed(MouseEvent e)
{
if(e.isPopupTrigger())
{
onShowPopup(e);
}
}
});
答案 1 :(得分:2)
这是一篇很棒的文章教程,我发现它帮助我完成了你想要完成的任务。
http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html#popup
我还发现了这个堆栈溢出文章的链接
How do I create a right click context menu in Java Swing?
希望这有帮助