5

複数選択ロジックを実装する JTree があります。

これは、マウス + Ctrl キーを押してすべての選択を行うとうまく機能します。ユーザーが Ctrl キーを押していない状態で選択すると、ロジックが壊れます。

壊れる理由はよくわかりませんが、可能な解決策は、Ctrlキーを押した状態で選択が行われたことをTreeSelectionModelに常に示すことだと思います。

何を提案しますか?

4

2 に答える 2

5

私は解決策を見つけたと思う

JTree と DefaultTreeSelectionModel を拡張する必要があります。

JTree 関連のメソッド:

/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
/// Implement selection using "adding" only logic. //
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////

@Override
public void setSelectionPath(TreePath path) {

    System.out.println("MLDebugJTree: setSelectionPath(" + path + ")");

    addSelectionPath(path);

    return;
    //super.setSelectionPath(path);
}

@Override
public void setSelectionPaths(TreePath[] paths) {

    System.out.println("MLDebugJTree: setSelectionPaths(" + paths + ")");

    addSelectionPaths(paths);

    return;
}

@Override
public void setSelectionRow(int row) {

    System.out.println("MLDebugJTree: setSelectionRow(" + row + ")");

    addSelectionRow(row);

    return;
    //super.setSelectionRow(row);
}

@Override
public void setSelectionRows(int[] rows) {

    System.out.println("MLDebugJTree: setSelectionRows(" + rows + ")");

    addSelectionRows(rows);

    return;
    //super.setSelectionRows(rows);
}

DefaultSelectionModel 関連メソッド:

package com.ml.tree2.model.impl;

import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.TreePath;

public class MLTreeSelectionModel extends DefaultTreeSelectionModel {
private static final long serialVersionUID = -4270031800448415780L;

@Override
public void addSelectionPath(TreePath path) {
    // Don't do overriding logic here because addSelectionPaths is ultimately called.
    super.addSelectionPath(path);
}

@Override
public void addSelectionPaths(TreePath[] paths) {
    if(paths != null) {
        for(TreePath path : paths) {

            TreePath[] toAdd = new TreePath[1];
            toAdd[0] = path;

            if (isPathSelected(path)) {
                // If path has been previously selected REMOVE THE SELECTION.
                super.removeSelectionPaths(toAdd);
            } else {
                // Else we really want to add the selection...
                super.addSelectionPaths(toAdd);
            }
        }
    }
}

HTH。

于 2009-03-31T15:26:11.690 に答える
3

もう 1 つの解決策は、単純に BasicTreeUI を拡張し、ニーズに合わせて選択動作を変更することです。

public class MultiSelectionTreeUI extends BasicTreeUI
{

    @Override
    protected boolean isToggleSelectionEvent( MouseEvent event )
    {
        return SwingUtilities.isLeftMouseButton( event );
    }
}

そして、その ui を JTree に設定します。

JTree tree = new JTree();
tree.setUI( new MultiSelectionTreeUI() );
于 2013-05-13T14:54:54.623 に答える