我有简单的代码示例。如何添加鼠标侦听器以显示选定 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);
}
}