问题:
通过鼠标事件覆盖实现 JLabel 的拖放,当在 mousePressed 事件中定义时, mouseReleased 事件无法在鼠标释放时触发。我做错了什么吗?”
代码:
<code class="java">Thumbnails[I_Loop].addMouseListener( new MouseAdapter() { public void mouseReleased(MouseEvent me) { System.out.println("here mouse released"); } public void mousePressed(MouseEvent me) { System.out.println("here mouse pressed"); JComponent comp = (JComponent) me.getSource(); TransferHandler handler = comp.getTransferHandler(); handler.exportAsDrag(comp, me, TransferHandler.COPY); });</code>
答案:
而@Thomas的解决方案是正确的,这里有两种可供考虑的替代方法:
1. 使用 JLayeredPane:
此示例演示了使用 JLayeredPane 拖动组件。 ,而最近的示例使用类似的方法。
代码:
<code class="java">// ... private Point mousePt; private Point dragPt; private Rectangle bounds; public MouseDragTest() { this.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { int dx = e.getX() - mousePt.x; int dy = e.getY() - mousePt.y; dragPt.setLocation(dragPt.x + dx, dragPt.y + dy); super.mouseDragged(e); } }); this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bounds = getBounds(); Point p = SwingUtilities.convertPoint(this, e.getPoint(), Bounds.Parent); if (bounds.contains(p)) { dragPt = p; mousePt = e.getPoint(); } } }); // ... }</code>
2. 使用 MouseMotionListener:
此代码演示了如何使用 MouseMotionListener。这个更复杂的示例使用相同的原理。
代码:
<code class="java">// ... private Point offset; public MouseDragTest() { this.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { Point delta = e.getPoint(); Point pt = new Point(getLocation().x + delta.x - offset.x, getLocation().y + delta.y - offset.y); setLocation(pt); } }); this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { offset = e.getPoint(); } }); // ... }</code>
以上是MousePressed 方法是否会禁止在 JLabel 拖放中触发 MouseReleased?的详细内容。更多信息请关注PHP中文网其他相关文章!