2

我正在尝试为 JTable 编写自定义的拖放行为,但无法接收MOUSE_DRAGGED事件。我猜问题是本机 DnD 操作消耗了该事件(如mouseDragged's javadoc:中"Due to platform-dependent Drag&Drop implementations, MOUSE_DRAGGED events may not be delivered during a native Drag&Drop operation. "所述),但我正在寻找一种方法来禁用它,或者解决它。

这是一个展示问题的 SSCCE:

public class DragAndDrop {
    @SuppressWarnings("serial")
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.getContentPane().add(
                new JTable(
                        new Object[][] {{1,2,3},{4,5,6}}, 
                        new Object[] {"one", "two", "three"}) 
                {{

                        addMouseListener(new MouseAdapter() {

                            @Override
                            public void mouseDragged(MouseEvent e) {
                                System.out.println("mouseDragged");
                            }

                            @Override
                            public void mousePressed(MouseEvent e) {
                                System.out.println("mousePressed");
                            }

                            @Override
                            public void mouseReleased(MouseEvent e) {
                                System.out.println("mouseReleased");
                            }

                        });
                }}
        );

        f.setVisible(true);
    }
}
4

1 回答 1

2
  • 使用正确的 Mouse(Xxx)Listener 并与 MouseAdapter 结合使用的唯一错误不会因异常而哭泣

  • 您添加了 MouseListener,正确的可能是 MouseListener 和 MouseMotionListener,您可以将这两个 Listener 拆分为两个单独的代码块(另一个可能的错误)TransferHandler

.

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTable;

public class DragAndDrop {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JTable(new Object[][]{{1, 2, 3}, {4, 5, 6}},
                new Object[]{"one", "two", "three"}) {
            {
                addMouseMotionListener(new MouseAdapter() {
                    @Override
                    public void mouseDragged(MouseEvent e) {
                        System.out.println("mouseDragged");
                    }

                    @Override
                    public void mousePressed(MouseEvent e) {
                        System.out.println("mousePressed");
                    }

                    @Override
                    public void mouseReleased(MouseEvent e) {
                        System.out.println("mouseReleased");
                    }
                });
            }
        });
        f.setVisible(true);
    }
}

run: 
mouseDragged mouseDragged mouseDragged 
mouseDragged mouseDragged 
BUILD STOPPED (total time: 1 minute 11 seconds)
于 2013-10-09T11:50:51.163 回答