2013-03-25 7 views
1

JPanel에서 사용할 수 있도록 JMenu의 팝업을 중앙에 배치하려고합니다. 여기에 몇 가지 코드가 내가 뭘하려고 오전 데모 버튼이 있습니다 :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

주의 : 비 표준 UI를 사용자에게 나는 페인트와 나는 많은 페인트가 어떻게하는지와 같은 폭을 설정하는 팝업을 표시하도록 메뉴를 사용하고 마이크로 소프트와 유사한 프로젝트를하고 있어요 – kleopatra

+0

@kleopatra을 혼동하는 경향이 . –

답변

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