JTable小区内的全功能JTree无法正常工作

时间:2016-10-12 23:37:59

标签: java swing jtable jtree

我试图获得一个将数据模型更新为表格单元格的JTree。使用现有的示例代码,我可以创建一个树,它将其复选框状态传递给另一个对象并保存它(摇摆示例没有做到)。我有一个JTable,它将呈现一个JTree,但是一旦树在表格的单元格中,它就不再响应用户输入。我已经尝试将鼠标监听器添加到表中,并使用dispatchEvent,但似乎没有做任何事情。

树嵌入到单元格中

Table Pic

只是树

Tree Pic

以下是来源:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import java.util.Vector;

import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;

public class CheckBoxNodeTreeSample {

    public static void main(String args[]) {
        JFrame frame = new JFrame("CheckBox Tree");

        CheckBoxNode accessibilityOptions[] = {
            new CheckBoxNode(
            "Move system caret with focus/selection changes", false),
            new CheckBoxNode("Always expand alt text for images", true)};
        CheckBoxNode browsingOptions[] = {
            new CheckBoxNode("Notify when downloads complete", true),
            new CheckBoxNode("Disable script debugging", true),
            new CheckBoxNode("Use AutoComplete", true),
            new CheckBoxNode("Browse in a new process", false)};
        Vector accessVector = new NamedVector("Accessibility",
                accessibilityOptions);
        Vector browseVector = new NamedVector("Browsing", browsingOptions);
        Object rootNodes[] = {accessVector, browseVector};
        Vector rootVector = new NamedVector("Root", rootNodes);
        JTree tree = new JTree(rootVector);

        CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
        tree.setCellRenderer(renderer);
        tree.setCellEditor(new CheckBoxNodeEditor(tree));
        tree.setEditable(true);
        tree.setRootVisible(true);


        String[] headers = {"this",
            "mixed"};
        Object[][] data = {{"the", tree}, {"other", "ifasdfasd"}};

        JTable table = new JTable(data, headers) {

            @Override
            public boolean isCellEditable(int i, int i1) {
                return false;
            }

        };
        table.setCellSelectionEnabled(false);
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable jtable, Object o, boolean bln, boolean bln1, int i, int i1) {
                if (o instanceof JTree) {
                    jtable.setRowHeight(((JTree) o).getPreferredSize().height + 20);
                    return ((JTree) o);
                }
                return super.getTableCellRendererComponent(jtable, o, bln, bln1, i, i1);
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}

class CheckBoxNodeRenderer implements TreeCellRenderer {

    private JCheckBox leafRenderer = new JCheckBox();

    private DefaultTreeCellRenderer nonLeafRenderer = new DefaultTreeCellRenderer();

    Color selectionBorderColor, selectionForeground, selectionBackground,
            textForeground, textBackground;

    protected JCheckBox getLeafRenderer() {
        return leafRenderer;
    }

    public CheckBoxNodeRenderer() {
        Font fontValue;
        fontValue = UIManager.getFont("Tree.font");
        if (fontValue != null) {
            leafRenderer.setFont(fontValue);
        }
        Boolean booleanValue = (Boolean) UIManager
                .get("Tree.drawsFocusBorderAroundIcon");
        leafRenderer.setFocusPainted((booleanValue != null)
                && (booleanValue.booleanValue()));

        selectionBorderColor = UIManager.getColor("Tree.selectionBorderColor");
        selectionForeground = UIManager.getColor("Tree.selectionForeground");
        selectionBackground = UIManager.getColor("Tree.selectionBackground");
        textForeground = UIManager.getColor("Tree.textForeground");
        textBackground = UIManager.getColor("Tree.textBackground");
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean selected, boolean expanded, boolean leaf, int row,
            boolean hasFocus) {

        Component returnValue;
        if (leaf) {

            String stringValue = tree.convertValueToText(value, selected,
                    expanded, leaf, row, false);
            leafRenderer.setText(stringValue);
            leafRenderer.setSelected(false);

            leafRenderer.setEnabled(tree.isEnabled());

            if (selected) {
                leafRenderer.setForeground(selectionForeground);
                leafRenderer.setBackground(selectionBackground);
            } else {
                leafRenderer.setForeground(textForeground);
                leafRenderer.setBackground(textBackground);
            }

            if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
                Object userObject = ((DefaultMutableTreeNode) value)
                        .getUserObject();
                if (userObject instanceof CheckBoxNode) {
                    CheckBoxNode node = (CheckBoxNode) userObject;
                    leafRenderer.setText(node.getText());
                    leafRenderer.setSelected(node.isSelected());
                }
            }
            returnValue = leafRenderer;
        } else {
            returnValue = nonLeafRenderer.getTreeCellRendererComponent(tree,
                    value, selected, expanded, leaf, row, hasFocus);
        }
        return returnValue;
    }
}

class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {

    CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();

    ChangeEvent changeEvent = null;

    JTree tree;
    CheckBoxNode checkBoxNode;

    public CheckBoxNodeEditor(JTree tree) {
        this.tree = tree;

    }

    public Object getCellEditorValue() {
        JCheckBox cb = renderer.getLeafRenderer();
        CheckBoxNode node = new CheckBoxNode(checkBoxNode.text, cb.isSelected());
        return node;
    }

    public boolean isCellEditable(EventObject event) {
        boolean returnValue = false;
        if (event instanceof MouseEvent) {
            MouseEvent mouseEvent = (MouseEvent) event;
            TreePath path = tree.getPathForLocation(mouseEvent.getX(),
                    mouseEvent.getY());
            if (path != null) {
                Object node = path.getLastPathComponent();
                if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                    Object userObject = treeNode.getUserObject();
                    returnValue = ((treeNode.isLeaf()) && (userObject instanceof CheckBoxNode));
                }
            }
        }
        return returnValue;
    }

    public Component getTreeCellEditorComponent(JTree tree, Object value,
            boolean selected, boolean expanded, boolean leaf, int row) {

        if (((DefaultMutableTreeNode) value).getUserObject() instanceof CheckBoxNode) {
            checkBoxNode = (CheckBoxNode) ((DefaultMutableTreeNode) value).getUserObject();
        }

        Component editor = renderer.getTreeCellRendererComponent(tree, value,
                true, expanded, leaf, row, true);

        // editor always selected / focused
        ItemListener itemListener = new ItemListener() {
            public void itemStateChanged(ItemEvent itemEvent) {
                if (stopCellEditing()) {
                    fireEditingStopped();
                }
            }
        };
        if (editor instanceof JCheckBox) {
            ((JCheckBox) editor).addItemListener(itemListener);
        }
        System.out.println(checkBoxNode);
        return editor;
    }
}

class CheckBoxNode {

    String text;

    boolean selected;

    public CheckBoxNode(String text, boolean selected) {
        this.text = text;
        this.selected = selected;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean newValue) {
        selected = newValue;
    }

    public String getText() {
        return text;
    }

    public void setText(String newValue) {
        text = newValue;
    }

    public String toString() {
        return getClass().getName() + "[" + text + "/" + selected + "]";
    }
}

class NamedVector extends Vector {

    String name;

    public NamedVector(String name) {
        this.name = name;
    }

    public NamedVector(String name, Object elements[]) {
        this.name = name;
        for (int i = 0, n = elements.length; i < n; i++) {
            add(elements[i]);
        }
    }

    public String toString() {
        return "[" + name + "]";
    }
}

1 个答案:

答案 0 :(得分:1)

此代码处理它,并且表现良好:

class JTreeCellEditor extends AbstractCellEditor
        implements TableCellEditor {
    Object obj;



    @Override
    public Object getCellEditorValue() {
        return obj; //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Component getTableCellEditorComponent(JTable jtable, Object o, boolean bln, int i, int i1) {
       obj = o;
        if (o instanceof JTree) {
            JTree tree = (JTree) o;

            tree.addTreeExpansionListener(new TreeExpansionListener() {

                @Override
                public void treeExpanded(TreeExpansionEvent event) {
                    jtable.setRowHeight(tree.getPreferredSize().height);
                }

                @Override
                public void treeCollapsed(TreeExpansionEvent event) {
                    jtable.setRowHeight(tree.getPreferredSize().height);
                }
            });
        }
        JTreeTableCellRenderer renderer = new JTreeTableCellRenderer();
        return renderer.getTableCellRendererComponent(jtable, o, bln, bln, i, i1);

    }
}

class JTreeTableCellRenderer extends DefaultTableCellRenderer {

    Object obj;

    @Override
    public Component getTableCellRendererComponent(JTable jtable, Object o, boolean bln, boolean bln1, int i, int i1) {
        if (o instanceof JTree) {
            JTree tree = (JTree) o;
            jtable.setRowHeight(tree.getPreferredSize().height);
            tree.addTreeSelectionListener(new TreeSelectionListener() {

                @Override
                public void valueChanged(TreeSelectionEvent e) {
                    jtable.setRowHeight(tree.getPreferredSize().height);
                }
            });
            return tree;
        }
        obj = o;
        return super.getTableCellRendererComponent(jtable, o, bln, bln1, i, i1);
    }
}