JPopupMenu is not working
I wrote a simple program to understand how JPopupMenu
works. But something is wrong with my code it doesn't show popup menu correctly. Please can someone tell me the reason?
public class PopUpMenu extends JFrame implements ActionListener {
JPanel panel;
JPopupMenu popMenu;
JMenuItem cut;
JMenuItem copy;
public PopUpMenu() {
setVisible(true);
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
popMenu = new JPopupMenu();
cut = new JMenuItem();
popMenu.add(cut);
copy = new JMenuItem();
popMenu.add(copy);
add(panel);
panel.setComponentPopupMenu(popMenu);
addMo开发者_如何转开发useListener(new MouseAdapter() {
public void mouseReleased(MouseEvent Me) {
if (Me.isPopupTrigger()) {
popMenu.show(Me.getComponent(), Me.getX(), Me.getY());
}
}
});
}
public void actionPerformed(ActionEvent arg0) {
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
PopUpMenu pop = new PopUpMenu();
}
};
SwingUtilities.invokeLater(r);
}
}
Your code is perfectible (the mouse listener is not needed, and the panel should be added to the content pane of the JFrame), but it works. Maybe it would seem to work better if you gave some text to your menu items :
cut = new JMenuItem("Cut");
Your MenuItem
size is 0
that is the reason I guess.
So, set some text for your MenuItem
.
cut = new JMenuItem("Cut");
...
copy = new JMenuItem("Copy");
精彩评论