我的代码:
class PanelGlowny extends JPanel implements ActionListener{}
public class Formatka extends JFrame implements ActionListener{
private JMenuItem klienciMenuItem = new JMenuItem("Klienci");
private JPopupMenu menuPopup = new JPopupMenu();
private PanelGlowny panelGlowny = new PanelGlowny();
public Formatka() {
add(panelGlowny, BorderLayout.CENTER);
menuPopup.add(klienciMenuItem);
panelGlowny.setComponentPopupMenu(menuPopup);
}
}
当我点击鼠标右键时,我看不到弹出菜单。 为什么?
答案 0 :(得分:8)
添加到JPanel
时适合我。
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
public class Formatka extends JPanel {
private JMenuItem klienciMenuItem = new JMenuItem("Klienci");
private JPopupMenu menuPopup = new JPopupMenu();
public Formatka() {
this.add(new JLabel("Right-click for popup menu."));
menuPopup.add(klienciMenuItem);
this.setComponentPopupMenu(menuPopup);
}
private void display() {
JFrame f = new JFrame("Formatka");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Formatka().display();
}
});
}
}
答案 1 :(得分:2)
您没有设置布局,因此该组件可能未添加到JFrame。使用setLayout(new BorderLayout());
将布局设置为JFrame。
答案 2 :(得分:1)
这适用于JFrame:D
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JFrame;
public class Popup extends JFrame{
JMenuItem item1,item2;
static JPopupMenu pop;
Popup(){
item1= new JMenuItem("This is Menu Item");
item2= new JMenuItem("This is another Menu Item");
pop= new JPopupMenu();
MouseListener popListener = new PopupListener();
pop.add(item1);
pop.add(item2);
addMouseListener(popListener);
setLocationRelativeTo(null);
pack();
setVisible(true);
}
public static void main(String a []){
new Popup();
}
}
class PopupListener extends MouseAdapter{
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
Popup.pop.show(e.getComponent(),
e.getX(), e.getY());
}
}
}