我想从数据库中获取数据并在jPopupMenu中显示它们,当点击弹出菜单中的菜单项时,想要打印它的text.i找到了一些教程,但我失败了。基本上我是什么'我正在以编程方式将manuitem添加到jpopupmenu并且我做了它.problem是如何从jpopupmenu获取选定值。例如我有popupmenu有两个菜单项和manuitems的文本是" menutext1"和#34; menutext2"。如果manuitem1被点击,我想打印menutext1。我想将动作监听器添加到jpopupmenu或每个菜单项?
while(rs1.next()){
jPopupMenu1.add(new JMenuItem(rs1.getString("name")));
jPopupMenu1.show(jPanel25, 40, 114);
}
答案 0 :(得分:3)
您可以为每个菜单项添加一个动作侦听器:
ActionListener menuListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("Popup menu item ["
+ event.getActionCommand() + "] was pressed.");
}
};
while(rs1.next()){
JMenuItem item = new JMenuItem(rs1.getString("name"));
item.addActionListener(menuListener);
jPopupMenu1.add(item);
}