如何启用JList中的拖放功能 [英] How to enable drag-and-drop inside JList

查看:148
本文介绍了如何启用JList中的拖放功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JList,希望用户能够使用drag-n-drop(使用我自己的ListModel和ListCellRenderer,如果有任何区别)重新排序列表中的元素。需要创建哪些对象,以及如何处理该操作?

I have a JList and want the user to be able to reorder the elements in the list using drag-n-drop (using my own ListModel and ListCellRenderer, if that makes any difference). Which Objects do I need to create, and how do I process the action?

推荐答案

修改Jan Taccis答案:

Modified Jan Taccis answer:

public class DndTest extends JFrame {

    JList<String> myList;
    DefaultListModel<String> myListModel;

    public DndTest() {
        myListModel = createStringListModel();
        myList = new JList<String>(myListModel);
        MyMouseAdaptor myMouseAdaptor = new MyMouseAdaptor();
        myList.addMouseListener(myMouseAdaptor);
        myList.addMouseMotionListener(myMouseAdaptor);

        JPanel content = new JPanel();
        content.add(myList);
        this.add(content);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }

    private class MyMouseAdaptor extends MouseInputAdapter {
        private boolean mouseDragging = false;
        private int dragSourceIndex;

        @Override
        public void mousePressed(MouseEvent e) {
            if (SwingUtilities.isLeftMouseButton(e)) {
                dragSourceIndex = myList.getSelectedIndex();
                mouseDragging = true;
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            mouseDragging = false;
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (mouseDragging) {
                int currentIndex = myList.locationToIndex(e.getPoint());
                if (currentIndex != dragSourceIndex) {
                    int dragTargetIndex = myList.getSelectedIndex();
                    String dragElement = myListModel.get(dragSourceIndex);
                    myListModel.remove(dragSourceIndex);
                    myListModel.add(dragTargetIndex, dragElement);
                    dragSourceIndex = currentIndex;
                }
            }
        }
    }

    private DefaultListModel<String> createStringListModel() {
        final String[] listElements = new String[] { "Cat", "Dog", "Cow", "Horse", "Pig", "Monkey" };
        DefaultListModel<String> listModel = new DefaultListModel<String>();
        for (String element : listElements) {
            listModel.addElement(element);
        }
        return listModel;
    }

    public static void main(String[] args) {
        new DndTest();
    }
}

这篇关于如何启用JList中的拖放功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆