获取JPopupMenu选择的项目索引可以通过以下步骤实现:
下面是一个示例代码:
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class PopupMenuExample {
public static void main(String[] args) {
JFrame frame = new JFrame("PopupMenu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add("Item 1");
popupMenu.add("Item 2");
popupMenu.add("Item 3");
JTextField textField = new JTextField();
textField.setBounds(50, 50, 150, 30);
textField.setComponentPopupMenu(popupMenu);
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
JPopupMenu menu = (JPopupMenu) e.getSource();
int selectedIndex = menu.getSelectionModel().getSelectedIndex();
textField.setText("Selected index: " + selectedIndex);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
frame.add(textField);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
在上述示例中,我们创建了一个JPopupMenu,并将其设置为JTextField的弹出菜单。在PopupMenuListener的popupMenuWillBecomeInvisible方法中,我们获取了选择的项目索引,并将其显示在JTextField中。
注意:这个示例中没有提及腾讯云相关产品和产品介绍链接地址,因为腾讯云与问题无关。
领取专属 10元无门槛券
手把手带您无忧上云