【发布时间】:2012-05-02 09:38:10
【问题描述】:
我正在开发一些 NetBeans 平台应用程序,目前我在 Visual Library 中遇到一些细节问题。好的,这里有问题。我的应用程序有可视化编辑器,带有托盘、场景,一切都很好,只是当我将图标从托盘拖到场景时出现问题。它们在拖动事件期间不显示,我想创建这种效果,有人可以帮忙吗?
【问题讨论】:
标签: java swing drag-and-drop icons netbeans-platform
我正在开发一些 NetBeans 平台应用程序,目前我在 Visual Library 中遇到一些细节问题。好的,这里有问题。我的应用程序有可视化编辑器,带有托盘、场景,一切都很好,只是当我将图标从托盘拖到场景时出现问题。它们在拖动事件期间不显示,我想创建这种效果,有人可以帮忙吗?
【问题讨论】:
标签: java swing drag-and-drop icons netbeans-platform
我分两个阶段进行:
1) 创建调色板元素的屏幕截图(图像)。我懒惰地创建屏幕截图,然后将其缓存在视图中。要创建屏幕截图,您可以使用这个 sn-p:
screenshot = new BufferedImage(getWidth(), getHeight(), java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE);// buffered image
// creating the graphics for buffered image
Graphics2D graphics = screenshot.createGraphics();
// We make the screenshot slightly transparent
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
view.print(graphics); // takes the screenshot
graphics.dispose();
2) 在接收视图上绘制屏幕截图。当识别到拖动手势时,找到一种方法使屏幕截图可用于接收视图或其祖先之一(您可以使其在框架或其内容窗格上可用,具体取决于您希望在何处使屏幕截图可用)并在paint方法中绘制图像。像这样的:
一个。提供屏幕截图:
capturedDraggedNodeImage = view.getScreenshot(); // Transfer the screenshot
dragOrigin = SwingUtilities.convertPoint(e.getComponent(), e.getDragOrigin(), view); // locate the point where the click was made
b.随着鼠标的拖动,更新截图的位置
// Assuming 'e' is a DropTargetDragEvent and 'this' is where you want to paint
// Convert the event point to this component coordinates
capturedNodeLocation = SwingUtilities.convertPoint(((DropTarget) e.getSource()).getComponent(), e.getLocation(), this);
// offset the location by the original point of drag on the palette element view
capturedNodeLocation.x -= dragOrigin.x;
capturedNodeLocation.y -= dragOrigin.y;
// Invoke repaint
repaint(capturedNodeLocation.x, capturedNodeLocation.y,
capturedDraggedNodeImage.getWidth(), capturedDraggedNodeImage.getHeight());
c。在paint方法中绘制屏幕截图:
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.drawImage(capturedDraggedNodeImage, capturedNodeLocation.x,
capturedNodeLocation.y, capturedDraggedNodeImage.getWidth(),
capturedDraggedNodeImage.getHeight(), this);
}
您可以在鼠标移动时调用paintImmediately(),而不是调用repaint() 并在paint() 方法中执行绘画,但是渲染会差很多,并且您可能会观察到一些闪烁,所以我不推荐该选项。使用paint() 和repaint() 可以提供更好的用户体验和流畅的渲染。
【讨论】:
如果我没听错的话,您正在创建某种图形编辑器,带有拖放元素,并且您想在拖放过程中创建效果?
如果是这样,您基本上需要创建您正在拖动的对象的幻影并将其附加到鼠标的移动中。当然,说起来容易做起来难,但你明白了要点。 所以你需要的是把你拖动的东西拍下来(应该不会太麻烦),然后根据鼠标的位置移动(想想你在对象中减去鼠标光标的相对位置) '正在拖动)。
但我认为这种代码在某处可用。我建议你查一下:
http://free-the-pixel.blogspot.fr/2010/04/ghost-drag-and-drop-over-multiple.html
http://codeidol.com/java/swing/Drag-and-Drop/Translucent-Drag-and-Drop/
希望对你有所帮助!
【讨论】: