昨天我问一个关于如何绘制一个边界框以保持内部形状和如何拖放所选形状的问题。
第一个问题已经解决。但是我在移动形状方面遇到了一些麻烦。是否有任何特定的转换来围绕jPanel移动形状?
我有这段代码:
public boolean drag(MouseEvent e) {
if(points.isEmpty()) //if point's vector is empty
return false;
if(!selected)
return false;
int x = e.getX(), y = e.getX();
if (!dragging)
lastMovePoint.setLocation(x, y);
dragging = true;
int deslocX = 0;
int deslocY = 0;
int oldX = -1;
int oldY = -1;
int size = points.size();
for(int i = 0; i < size; i++) {
oldX = lastMovePoint.x;
oldY = lastMovePoint.y;
deslocX = x - oldX;
deslocY = y - oldY;
points.set(i, new Point(points.get(i).x + deslocX, points.get(i).y + deslocY));
//set the vector of points so that when there is a repaint() it repaints the shape with the new
//coordinates
}
lastMovePoint.setLocation(x, y); //set the location of the old point
return true;
}
此方法由侦听器mouseDragged调用,并在成功时返回true。我试图做的是添加前一个拖拽点与实际值之间的差异。
当我运行此代码时,我遇到了一个问题:
形状只向右/向左,向上和向下不起作用......
答案 0 :(得分:5)
是的,为了拖动组件,您还需要知道起始位置,以便计算鼠标移动的距离。
以下是一些显示移动窗口的一般行为的代码。
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class MoveWindow extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me)
{
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
private static void createAndShowGUI()
{
JWindow window = new JWindow();
window.setSize(300, 300);
window.setLocationRelativeTo( null );
window.setVisible(true);
MouseInputAdapter listener = new MoveWindow();
window.addMouseListener( listener );
window.addMouseMotionListener( listener );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
我允许您为您的目的实施它。
答案 1 :(得分:2)
int x = e.getX(), y = e.getX();
这应该改为
int x = e.getX(), y = e.getY();
这就是为什么它只在x方向起作用,你实际上并没有考虑Y方向