过去,当一个JPopupMenu
可见时,默认情况下会选择第一项:http ://weblogs.java.net/blog/alexfromsun/archive/2008/02/jtrayicon_updat.html
如今,默认行为是弹出菜单而不选择任何项目。我想创建一个JPopupMenu
带有单个项目的项目,该项目将在鼠标指针下弹出并居中。我设法让该项目在鼠标下方居中弹出,但我JMenuItem
拒绝渲染,就好像它被选中一样。如果我将鼠标移出项目并重新选择正确。
有任何想法吗?
这是我的测试用例:
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class Test extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.getContentPane().addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e)
{
if (e.isPopupTrigger())
popupTriggered(e);
}
@Override
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
popupTriggered(e);
}
private void popupTriggered(MouseEvent e)
{
JPopupMenu menu = new JPopupMenu();
final JMenuItem item = new JMenuItem("This is a JMenuItem");
menu.add(item);
Point point = e.getPoint();
int x = point.x - (item.getPreferredSize().width / 2);
int y = point.y - (item.getPreferredSize().height / 2);
menu.show((Component) e.getSource(), x, y);
}
});
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}