在JTable上执行拖放操作时,会显示拖动时显示的所选单元格(选择框)的轮廓。我怎样才能覆盖那种行为而不显示任何东西,除了可能是一个特殊的光标?
在Windows和OSX中运行以下代码显示了我想要覆盖的行为!
import java.awt.BorderLayout;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class GestureTest
extends
JFrame
implements
DragGestureListener {
private final DragSource ds;
private final JTable jl;
private static final Object[][] ITEMS = { { "Java" }, { "C" }, { "C++" }, { "Lisp" },
{ "Perl" }, { "Python" } };
public GestureTest() {
super("Gesture Test");
setSize(200, 150);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent we) {
System.exit(0);
}
});
jl = new JTable(ITEMS, new Object[] { "Langs" });
jl.setDragEnabled(true);
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
getContentPane().add(new JScrollPane(jl), BorderLayout.CENTER);
ds = new DragSource();
// final DragGestureRecognizer dgr =
ds.createDefaultDragGestureRecognizer(
jl, DnDConstants.ACTION_MOVE, this);
setVisible(true);
}
@Override
public void dragGestureRecognized(final DragGestureEvent dge) {
System.out.print("dragGestureRecognized");
}
public static void main(final String args[]) {
new GestureTest();
}
}
答案 0 :(得分:0)
我找到了一个解决方案,尽管你必须自己写一些dnd处理。
首先禁用JTable自己的dnd处理:jl.setDragEnabled(false);
然后,您可以使用以下代码dragGestureRecognized
方法自行调用startDrag
。
重要的一位是empty
图像。在这里使用null
将导致操作系统显示特定于操作系统的图像(Windows不显示,OS X灰色框),在此处明确设置图像将导致显示该图像(空白的1x1像素图像)我们的情况)。
@Override
public void dragGestureRecognized(final DragGestureEvent dge) {
System.out.print("dragGestureRecognized");
Transferable transferable = new Transferable() {
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return true;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.stringFlavor };
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return "Hello world!";
}
};
BufferedImage empty = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
dge.startDrag(null, empty, new Point(), transferable, null);
}