我有这段代码,它应该在释放鼠标按钮时移动一些像素:
if (selected != -1) {
Point to = e.getPoint();
int dx = start.x - to.x;
int dy = start.y - to.y;
for (Point p: store.get(selected)) {
int px = (int) p.getX();
int py = (int) p.getY();
p.move(px - dx, py - dy);
}
validate();
调试器的使用表明点 p 确实获得了新值,但视觉效果没有得到更新。请帮帮我。
下面是我的程序的全部代码。
public class Pisi extends JFrame implements MouseMotionListener, MouseListener {
ArrayList<ArrayList<Point>> store = new ArrayList<ArrayList<Point>>();
ArrayList<Point> pts = new ArrayList<Point>();
Point start;
static int xsize = 450;
static int ysize = 300;
int listNumber = 0;
int selected = -1;
public static void main(String[] args) {
Pisi d = new Pisi();
d.setSize(xsize, ysize);
d.setLocationRelativeTo(null);
d.addMouseMotionListener(d);
d.addMouseListener(d);
d.setResizable(false);
d.setVisible(true);
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public void paint(Graphics g) {
Point last = null;
for (Point p : pts) {
if (last == null) {
last = p;
continue;
}
g.drawLine(last.x, last.y, p.x, p.y);
last = p;
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
pts.add(e.getPoint());
repaint();
}
}
@Override
public void mouseMoved(MouseEvent e) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void mouseClicked(MouseEvent e) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void mousePressed(MouseEvent e) {
Point point = e.getPoint();
start = null;
selected = -1;
for (ArrayList<Point> points: store) {
for (Point p : points) {
double dist = point.distanceSq(p);
if (dist < 10) {
selected = store.indexOf(points);
}
}
}
if (selected != -1) {
start = e.getPoint();
}
System.out.println(selected);
}
@Override
public void mouseReleased(MouseEvent e) {
if (selected != -1) {
Point to = e.getPoint();
int dx = start.x - to.x;
int dy = start.y - to.y;
for (Point p: store.get(selected)) {
int px = (int) p.getX();
int py = (int) p.getY();
p.move(px - dx, py - dy);
}
validate();
} else if (e.getButton() == MouseEvent.BUTTON1 && pts.size() != 0) {
store.add(new ArrayList<Point>(listNumber));
for (int i = 0; i < pts.size(); i++) {
store.get(listNumber).add(pts.get(i));
}
listNumber++;
}
pts.clear();
}
@Override
public void mouseEntered(MouseEvent e) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
//To change body of implemented methods use File | Settings | File Templates.
}
}