做界面时,常用到快捷菜单(JPopupMenu), 可JPopupMenu本身没办法根据鼠标位置来自动调整菜单位置使全部菜单可见,为此我专门写了一个可自适应位置的快捷菜单,代码如下:
import javax.swing.*;
import java.awt.*;
/**
* <p>Copyright: Copyright (c) 2002</p>
* @author Turbo Chen
* @version 1.01
*/
public class CJPopupMenu extends JPopupMenu
{
public void show(Component invoker,int x, int y)
{
Point ps = invoker.getLocationOnScreen();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int mw = this.getPreferredSize().width;
int mh = this.getPreferredSize().height;
int newX = x;
int newY = y;
int aX = ps.x+x+mw;
int aY = ps.y+y+mh;
if ( aX>d.width )
newX = x -(aX - d.width);
if ( aY>d.height )
newY = y -(aY - d.height);
super.show(invoker,newX,newY);
}
}
这个类重载了public void show(Component invoker,int x, int y)方法来实现自适应位置功能.