我有一个JComponent
,其中包含JMenuBar
。我希望能够通过单击它并将鼠标拖动到所需位置来拖动组件。我已经通过将MouseInputAdapter
方法添加到其Border
来实现此功能,并且效果很好。
但是,我想在JMenuBar
上应用相同的功能,mouseDragged()
方法不会被调用。
这是菜单监听器(用于测试的剥离版本):
menuBar.addMouseListener(new MouseInputAdapter() {
private Point startPos = null;
@Override
public void mousePressed(MouseEvent me) {
startPos = me.getPoint();
// works fine
System.out.println("startPos: " + startPos.toString());
}
@Override
public void mouseDragged(MouseEvent me) {
// this does not get called...
System.out.println("dragging.............");
}
});
我不认为这是问题,但这里是整个组件使用的Listener。这两个听众会不会碰撞?我试图删除这个听众,但它没有解决任何问题:
// this works with the border
this.addMouseListener(resizeListener);
MouseInputListener resizeListener = new MouseInputAdapter() {
@Override
public void mouseEntered(MouseEvent me) {
// put this widget on top when mouse moves across it
putOnTop();
}
@Override
public void mouseMoved(MouseEvent me) {
// put this widget on top when mouse moves across it
putOnTop();
WidgetBorder border = (WidgetBorder) getBorder();
setCursor(Cursor.getPredefinedCursor(border.getResizeCursor(me)));
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
setCursor(Cursor.getDefaultCursor());
}
private int cursor;
private Point startPos = null;
@Override
public void mousePressed(MouseEvent me) {
WidgetBorder border = (WidgetBorder) getBorder();
cursor = border.getResizeCursor(me);
startPos = me.getPoint();
}
@Override
public void mouseDragged(MouseEvent me) {
if (startPos != null) {
// widget cant be resized under its minimum size
if (widget.getWidth() < WidgetConstants.MIN_WIDTH) {
widget.setBounds(widget.getX(), widget.getY(), WidgetConstants.MIN_WIDTH + 1, widget.getHeight());
return;
}
if (widget.getHeight() < WidgetConstants.MIN_HEIGHT) {
widget.setBounds(widget.getX(), widget.getY(), widget.getWidth(), WidgetConstants.MIN_HEIGHT + 1);
return;
}
int dx = me.getX() - startPos.x;
int dy = me.getY() - startPos.y;
switch (cursor) {
case Cursor.SE_RESIZE_CURSOR:
setBounds(getX(), getY(), getWidth() + dx, getHeight() + dy);
startPos = me.getPoint();
repaintParent();
break;
case Cursor.MOVE_CURSOR:
Rectangle bounds = getBounds();
bounds.translate(dx, dy);
setBounds(bounds);
repaintParent();
}
// cursor shouldn't change while dragging
setCursor(Cursor.getPredefinedCursor(cursor));
}
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
startPos = null;
}
};
我在这里缺少什么?谢谢你的帮助...
答案 0 :(得分:2)
MouseInputAdapter
实现了许多接口(例如MouseListener
,MouseMotionListener
等。)
您必须使用多种方法添加此方法,例如如果您希望调用Component.addMouseListener()
,请mouseClicked()
Component.addMouseMotionListener()
,如果希望调用mouseDragged()
Component.addWheelListener()
,mouseWheelMoved()
Component.addMouseListener()
调用。
当然,您可以传递相同的引用,但必须使用多种方法添加侦听器实现。原因是因为例如MouseListener
需要一个MouseListener
接口,并且只会调用{{1}}接口中定义的方法,即使您从其他接口传递实现其他方法的对象也是如此。