Piumi Wandana
Piumi Wandana

Reputation: 228

get selected value from jpopupmenu

i want to get data set from database and show them in a jPopupMenu and when clicked a menu-item in popupmenu want to print it's text.i found some tutorials but i failed .basically what i'm doing is add manuitem programmatically into jpopupmenu and i did it.problem is how to get selected value from jpopupmenu .for example i have popupmenu with two menu-items and text of manuitems are "menutext1" and "menutext2".so i want to print menutext1 if manuitem1 get clicked.do i want to add action listener to jpopupmenu or to each menu items ?

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

Upvotes: 2

Views: 3761

Answers (1)

Gavin Black
Gavin Black

Reputation: 136

You could add an action listener to each menu item:

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

Upvotes: 3

Related Questions