我有两个听众, 一个是MouseWheelListener,如果滚动滚轮,它将放大图像。
jLabel1.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
double temp = zoom - (notches * 0.2);
// minimum zoom factor is 1.0
temp = Math.max(temp, 1.0);
if (temp != zoom) {
zoom = temp;
Map.resizeImage(jLabel1,zoom);
}
}
});
放大时,我需要能够使用拖动侦听器在图像上拖动,我已经创建了侦听器并将其注册到jScrollPanel中,如下所示:
HandScrollListener scrollListener = new HandScrollListener(jLabel1);
jScrollPane1.getViewport().addMouseMotionListener(scrollListener);
jScrollPane1.getViewport().addMouseListener(scrollListener);
问题是,如果我添加了放大图像的第一个侦听器,则会生成第二个侦听器,但不执行其拖动功能。如果我将其删除并使用按钮放大图像,则将生成第二个侦听器并执行其拖动功能。
这里是HandScrollListener,它在未添加放大侦听器时起作用。
public class HandScrollListener extends MouseAdapter
{
Cursor defCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
Cursor hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
Point pp = new Point();
public void mouseDragged(final MouseEvent e)
{
JViewport vport = (JViewport)e.getSource();
Point cp = e.getPoint();
Point vp = vport.getViewPosition();
vp.translate(pp.x-cp.x, pp.y-cp.y);
image.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
pp.setLocation(cp);
}
public void mousePressed(MouseEvent e)
{
image.setCursor(hndCursor);
pp.setLocation(e.getPoint());
}
public void mouseReleased(MouseEvent e)
{
image.setCursor(defCursor);
image.repaint();
}
}