2013-03-25 33 views
1

我想中心一個JMenu的彈出窗口,所以我可以在JPanel上使用它,它不會關閉。下面是一些代碼,演示什麼,我試圖做的:你會如何集中JMenu的Popup?

import javax.swing.*; 

public class Menu extends JMenu{ 

public static void main(String[] args) {   
    JFrame f = new JFrame("Menu Test"); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JMenuBar menuBar = new JMenuBar(); 
    menuBar.add(new Menu()); 

    JPanel background = new JPanel(); 
    background.add(menuBar); 
    f.setContentPane(background); 

    f.setSize(250, 100); 
    f.setLocationRelativeTo(null); 
    f.setVisible(true); 
} 

public Menu() { 
    super("I'm a Menu"); 

    add(new JMenuItem("Can This Popup be Centered?")); 
    add(new JMenuItem("Not To the Right?")); 
} 
} 

下面是電流輸出

Here is an image of the output

這就是我想要的(或接近)

Here is (close to) what I want

如果除了使用JMenu之外還有其他更好的方法,請讓我知道。 謝謝。

+0

要注意:非標UIS往往迷惑用戶 – kleopatra 2013-03-25 07:48:26

+0

@kleopatra我在做類似微軟的一個項目塗料及我使用的菜單顯示一個彈出設置寬度像油漆是如何做的很多。 – 2013-03-27 05:26:35

回答

1

我想出了答案。我重寫processMouseEvent來知道菜單何時被點擊,而不是簡單地設置相對於菜單位置的彈出式菜單的位置。

@Override 
    protected void processMouseEvent(MouseEvent e) { 
     super.processMouseEvent(e); 
     if(e.getID() == MouseEvent.MOUSE_PRESSED) 
      getPopupMenu().setLocation(
       getLocationOnScreen().x+getWidth()/2-getPopupMenu().getWidth()/2, 
       getLocationOnScreen().y+getHeight()); 
}