Java Отключить действие вырезания для JTree / TransferHandler - PullRequest
1 голос
/ 26 июля 2011

Я создал собственный TransferHandler для моего JTree и поэтому отключил Copy (только поддерживая Move) и Paste (проверив support.isDrop () в canImport), но я не могу понять, как отключить Cutоперация.

Похоже, мне нужно сделать определение в методе exportDone, но пока не повезло.Пока мой метод выглядит так, но Drag и Cut связаны с действием Move.

protected void exportDone(JComponent source, Transferable data, int action) {
    if(action == TransferHandler.MOVE) {
        try {
            List<TreePath> list = ((TestTreeList) data.getTransferData(TestTreeList.testTreeListFlavor)).getNodes();

            int count = list.size();
            for(int i = 0; i < count; i++) {
                TestTreeNode        node    = (TestTreeNode) list.get(i).getLastPathComponent();
                DefaultTreeModel    model   = (DefaultTreeModel) tree.getModel();
                model.removeNodeFromParent(node);
            }
            tree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        } catch (UnsupportedFlavorException e) {
            Log.logException(e);
        } catch (IOException e) {
            Log.logException(e);
        }
    }
}

Ответы [ 3 ]

0 голосов
/ 03 ноября 2015

JTree «WHEN_FOCUSED» InputMap, но не первое «поколение»: у InputMaps могут быть «родительские» (прародители, прародители и т. Д.) InputMap (s).

tree.getInputMap( JComponent.WHEN_FOCUSED ).getParent().remove( KeyStroke.getKeyStroke( KeyEvent.VK_X, KE.CTRL_DOWN_MASK ) )

ВНИМАНИЕ: во избежание частых царапин, вы также можете узнать, что существует «иерархия» (или, точнее, порядок «консультации») между различными типами InputMap: сначала выполняется WHEN_FOCUSED, затем WHEN_ANCESTOR и, наконец, WHEN_IN_FOCUSED_WINDOW. Если вы поместите Ctrl-X во входную карту WHEN_ANCESTOR объекта JComponent (возможно, надеясь, что он переопределит то, что уже есть), это будет «затмено», если во входной карте WHEN_FOCUSED того же JComponent есть Ctrl-X.

Достигнуть много просветления можно, сделав простой метод для изучения всей иерархии по сравнению с данным компонентом, показывая все привязки клавиш (по крайней мере, в иерархии с повышением: отображение всех нажатий клавиш WHEN_IN_FOCUSED_WINDOW в данном окне - немного больше участвует).

Я пользователь Jython, но это должно быть понятно: похожая (но неизбежно менее изящная) утилита может быть написана на Java.

def show_ancestor_comps( comp, method ):
    height = 0
    while comp:
        if method:
            # this method can return True if it wants the ancestor exploration to stop
            if method( comp, height ):
                return
        height = height + 1
        comp = comp.parent

''' NB this can be combined with the previous one: show_ancestor_comps( comp, show_all_inputmap_gens_key_value_pairs ):
gives you all the InputMaps in the entire Window/Frame, etc. ''' 
def show_all_inputmap_gens_key_value_pairs( component, height ):
    height_indent = '  ' * height
    if not isinstance( component, javax.swing.JComponent ):
        logger.info( '%s# %s not a JComponent... no InputMaps' % ( height_indent, type( component ), ))
        return
    logger.info( '%s# InputMap stuff for component of type %s' % ( height_indent, type( component ), ))
    map_types = [ 'when focused', 'ancestor of focused', 'in focused window' ]
    for i in range( 3 ):
        im = component.getInputMap( i )
        logger.info( '%s# focus type %s' % ( height_indent, map_types[ i ], ))
        generation = 1
        while im: 
            gen_indent = '  ' * generation
            logger.info( '%s%s# generation %d InputMap %s' % ( height_indent, gen_indent, generation, im, )) 
            if im.keys():
                for keystroke in im.keys():
                    logger.info( '%s%s# keystroke %s value %s' % ( height_indent, gen_indent + '  ', keystroke, im.get( keystroke )))
            im = im.parent
            generation += 1
0 голосов
/ 04 апреля 2017
    ActionMap actionMap = tree.getActionMap();
    actionMap.put( "cut", null );
    actionMap.put( "copy", null );
    actionMap.put( "paste", null );

    actionMap.getParent().put( "cut", null );
    actionMap.getParent().put( "copy", null );
    actionMap.getParent().put( "paste", null );
0 голосов
/ 26 июля 2011

Вы также можете отключить CUT, COPY, PASTE из пользовательского интерфейса, удалив действия из ActionMap.

JTree tree = new JTree();
...
tree.getActionMap().put( "cut", null );
tree.getActionMap().put( "copy", null );
tree.getActionMap().put( "paste", null );

Это мешает кому-либо копировать, вырезать или вставлять, используя это дерево в качестве источника.

...