我想从数据库中获取数据集并将其显示在jPopupMenu中,并在popupmenu中单击菜单项时要打印它的text.i找到了一些教程,但是我失败了。基本上,我的工作是将程序以编程方式添加到jpopupmenu中,我做到了。问题是如何从jpopupmenu中获取选定的值。例如,我有带有两个菜单项的popupmenu,manuitem的文本是“ menutext1”和“ menutext2”。因此,如果要单击manuitem1,我想打印menutext1。我是否要将动作侦听器添加到jpopupmenu或每个菜单项?

while(rs1.next()){
   jPopupMenu1.add(new JMenuItem(rs1.getString("name")));
   jPopupMenu1.show(jPanel25, 40, 114);
}

最佳答案

您可以将动作侦听器添加到每个菜单项:

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);
}

关于java - 从jpopupmenu获取选定的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25768060/

10-11 10:52