如何移动JFrame
拥有自定义标题栏?
我删除了默认的标题栏,我做了自己的设计。这就是它的样子:
我想知道当光标仅放置在标题栏而不是整个框架时如何拖动JFrame
。我已经搜索过,我看过很多样本,但我还是没有得到它。你们有任何我能理解的简单代码吗?
我还没有启动代码,因为我不知道如何启动它。我所知道的只是mouseDragged
或MouseMotionListener
。
答案 0 :(得分:1)
我实施了以下内容:
public class DragFrame extends JFrame {
int mpX, mpY;
public DragFrame() {
addMouseListener( new MouseAdapter() {
@Override
public void mousePressed( MouseEvent e ) {
mpX = e.getX();
mpY = e.getY();
}
} );
addMouseMotionListener( new MouseMotionAdapter() {
@Override
public void mouseDragged( MouseEvent e ) {
setLocation(
getLocation().x + e.getX() - mpX,
getLocation().y + e.getY() - mpY );
}
} );
}
}
感谢 @peeskillet 提供了Drag and Resize undecorated JFrame的关键链接,其灵感来源于mousePressed(...)
上的鼠标位置。
答案 1 :(得分:0)
您猜测您需要覆盖MoseMotionListener.mouseDragged
方法是正确的。然后,您需要致电JFrame.setLocation
移动JFrame
,如下所示:
class FrameMoveListener extends MouseAdapter
{
private Point lastPos;
private Frame frame;
public FrameMoveListener (Frame f)
{
frame = f; // mustn't be null
}
public void mouseDragged (MouseEvent evt)
{
if (lastPos != null)
{
int x = lastPos.x - evt.getX();
int y = lastPos.y - evt.getY();
f.setLocation(f.getLocationOnScreen().x + x,
f.getLocationOnScreen().y + y);
}
lastPos = new Point(evt.getX(), evt.getY());
}
}
答案 2 :(得分:0)
使用此方法简单且完善
final Component obj - 你的JFrame,JLabel,任何Component 最终布尔信息 - 如果要在释放左侧单击时显示位置
public static void Move(final Component obj,final boolean info) {
MouseInputAdapter d=new MouseInputAdapter() {int x,X,y,Y;
@Override public void mousePressed(MouseEvent e){if(SwingUtilities.isLeftMouseButton(e)){x=e.getXOnScreen();X=obj.getLocation().x;y=e.getYOnScreen();Y=obj.getLocation().y;}}
@Override public void mouseDragged(MouseEvent e){if(SwingUtilities.isLeftMouseButton(e)){obj.setLocation(X+(e.getXOnScreen()-x), Y+(e.getYOnScreen()-y));}}
@Override public void mouseReleased(MouseEvent e){if(info && SwingUtilities.isLeftMouseButton(e)){System.err.println(obj.toString().substring(0,obj.toString().indexOf("["))+" ("+obj.getLocation().x+","+obj.getLocation().y+")");}}};
obj.addMouseListener(d);obj.addMouseMotionListener(d);
}
这是格式代码:
public static void Mover(final Component obj, final boolean info) {
MouseInputAdapter d = new MouseInputAdapter() {
int x, X, y, Y;
@Override public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
x = e.getXOnScreen();
X = obj.getLocation().x;
y = e.getYOnScreen();
Y = obj.getLocation().y;
}
}
@Override public void mouseDragged(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
obj.setLocation(X + (e.getXOnScreen() - x), Y + (e.getYOnScreen() - y));
}
}
@Override public void mouseReleased(MouseEvent e) {
if (info && SwingUtilities.isLeftMouseButton(e)) {
System.err.println(obj.toString().substring(0, obj.toString().indexOf("[")) + " (" + obj.getLocation().x + "," + obj.getLocation().y + ")");
}
}
};
obj.addMouseListener(d);
obj.addMouseMotionListener(d);
}