`
hcx_2008
  • 浏览: 122091 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

swing checkbox tree

    博客分类:
  • J2SE
阅读更多
//有点小BUG未解决
package cn.anhong.tools;

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

import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
*
* @author anhong
*/
public class CheckBoxNodeTreeSample {

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

        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);
        final JTree tree = new JTree(rootVector);

        CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
        tree.setCellRenderer(renderer);

        tree.setCellEditor(new CheckBoxNodeEditor(tree));
        tree.setEditable(true);
        for (int i = 0; i < tree.getRowCount(); i++) {
            tree.expandRow(i);
        }

        JScrollPane scrollPane = new JScrollPane(tree);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        JButton button = new JButton("测试");
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                TreeNode root = (TreeNode) tree.getModel().getRoot();
                StringBuilder buffer = new StringBuilder();
                buffer.append("---\r\n");
                for (int i = 0; i < root.getChildCount(); i++) {
                    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) root.getChildAt(i);
                    NamedVector vt = (NamedVector) parent.getUserObject();
                    buffer.append(vt.toText());
                    buffer.append("\r\n");
                }
                buffer.append("---");
                JTextArea area = new JTextArea(5, 30);
                area.setText(buffer.toString());
                JScrollPane panel = new JScrollPane(area);
                JOptionPane.showMessageDialog(frame, panel);
            }
        });
        frame.getContentPane().add(button, BorderLayout.SOUTH);

        frame.setSize(600, 450);
        frame.setLocationRelativeTo(null);
        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;

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

    public Object getCellEditorValue() {
        JCheckBox checkbox = renderer.getLeafRenderer();
        CheckBoxNode checkBoxNode = new CheckBoxNode(checkbox.getText(),
                checkbox.isSelected());
        return checkBoxNode;
    }

    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) {

        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 box = (JCheckBox) editor;
            box.addItemListener(itemListener);
        }

        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 "<" + 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 + "]";
    }

    public String toText() {
        return "[" + name + "]" + Arrays.toString(this.toArray());
    }
}
分享到:
评论

相关推荐

    CheckBoxTree

    10. **编程语言与框架**:CheckBoxTree可以使用多种编程语言实现,如JavaScript(搭配React、Vue或Angular等前端框架)、Java(在Swing或JavaFX中)、C#(在WPF或WinForms中)等。每种语言和框架都有其特定的实现...

    Java中带复选框的树(Java CheckBox Tree)的实现和应用.doc

    有了自定义的 TreeNode 和 TreeCellRenderer,我们可以创建一个 CheckBoxTree 并设置它。下面是如何在 Java Swing 应用程序中使用这些组件的示例: ```java import javax.swing.*; import javax.swing.tree....

    checkBoxTree 树

    在Java中,比如使用Swing或JavaFX可以创建桌面应用的`checkBoxTree`;在Web开发中,JavaScript库如jQuery、React、Vue或Angular等可以用来构建前端的`checkBoxTree`。这里的标签提到了“java js”,表明实现可能是跨...

    JTree(节点带有checkbox)代码实例2

    import javax.swing.tree.TreeCellRenderer; import javax.swing.*; import java.awt.*; public class CheckboxTreeCellRenderer extends DefaultTreeCellRenderer { private JCheckBox checkbox; public ...

    Java带复选框的树(Java CheckBox Tree)实现和应用

    Java带复选框的树(Java CheckBox Tree)是一种特殊的树形控件,在Java Swing开发中经常被使用。它的实现和应用主要包含了以下几个方面的知识点: 首先,Java CheckBox Tree与JTree的区别在于CheckBox Tree的每个...

    JTree(节点带有checkbox)代码实例

    首先,我们需要导入必要的Java Swing库,包括`javax.swing.JTree`、`javax.swing.tree.DefaultTreeModel`、`javax.swing.tree.DefaultMutableTreeNode`等。`DefaultMutableTreeNode`用于构建树结构,`...

    TreeCheckBox

    - 对于Java开发者,可以使用Swing或JavaFX库中的JTree和DefaultTreeModel,结合自定义CellRenderer来创建TreeCheckBox。 - 对于.NET平台,WinForms或WPF框架提供了TreeView控件,可以添加CheckBoxes并设置其属性。 -...

    chekboxtree

    在IT领域,CheckboxTree是一种常见的UI元素,尤其在数据管理和配置界面中十分流行。它将树形结构的数据与复选框相结合,用户可以通过选择或取消选择节点来对数据进行操作。这种控件允许用户批量选择或者层级选择,...

    swing复选框树

    在Java Swing库中,"复选框树"(Checkbox Tree)是一种可视化的组件,它将树形结构的数据与复选框结合,用户可以选择或取消选择树中的节点。这个组件非常适合于展示具有层次关系且需要多选操作的数据。下面我们将...

    java Swing带复选框的树

    Java Swing 是Java GUI(图形用户界面)库的一部分,它提供了丰富的组件来构建桌面应用程序。在Swing中,我们可以创建各种用户界面元素,如按钮、文本框、面板等,其中包括树形视图(JTree)。在描述中提到的“java ...

    TreeTableJava实现树形结构表格

    treeTable是跨浏览器、性能很高的jquery的树表组件,它使用非常简单,只需要引用jquery库和一个js文件,接口也很简单。 优点 兼容主流浏览器: 支持IE6和IE6+, Firefox, chrome, Opera, Safari ...

    带复选框的多级目录树,复选框的选择控制子节点父节点 全选和反选

    例如,React中有许多第三方库如`react-checkbox-tree`、`antd`的Tree组件等,它们内置了全选、反选和级联选择的功能。 总结来说,带复选框的多级目录树是一种高效的数据组织和操作方式,结合全选和反选功能,能极大...

    swing实例仿window

    2. **选项框(Checkbox)**: `JCheckBox`是Swing中的复选框组件,允许用户选择一个或多个选项。用户可以选择或取消选择,可以通过`isSelected()`方法检查当前状态,并使用`setSelected()`来改变状态。可以将`...

    JIDE_Common_Layer_Developer_Guide.pdf

    CheckboxTree是树形组件的扩展,它为树节点提供了复选框,从而可以实现多选功能。这两个组件都极大地提升了用户界面的互动性和可用性。 RangeSlider是另一种组件,它允许用户在一个滑动范围内选择值。它特别适合于...

    (一)如何使用JTree

    JTree是javax.swing.tree包中的一个类,它允许用户通过树状结构浏览数据。每个节点可以有子节点,形成一个可展开和折叠的层次结构。节点通常由DefaultMutableTreeNode类表示,它们可以容纳自定义的数据对象。 创建...

    jtree

    在Java的Swing库中,`JTree`组件是一个用于展示层次数据的控件,它以树状结构显示数据。`jtree`标题所指的可能是关于如何在`JTree`中添加复选框(checkboxes)的功能。这通常是为了让用户能够多选树中的节点,进行...

    JTree with JCheckBox的资料整理

    在Java Swing库中,`JTree`是一个组件,用于显示层次结构的数据,而`JCheckBox`则是一个可以勾选或取消勾选的图形用户界面元素。将`JCheckBox`与`JTree`结合使用,可以在树形结构的节点上提供复选框功能,允许用户...

    android 树形复选框

    一个项目用Swing写了一个节点带有Checkbox的树状控件,并有3...SWT的Tree控件本身就可以在节点上加上Checkbox。这也是我喜欢SWT的一个原因。 顺带的,也尝试了一下把一个AWT/Swing控件加到SWT的Composite上,效果非常好

    Java程序设计之swt教程.rar

    - Button、Label、Text、Checkbox、RadioButton等:这些是常见的控件,用于构建用户界面。 - ScrollBar:提供滚动功能,用于处理大量数据的显示。 - Tree和Table:用于展示层次化或表格数据。 4. SWT事件处理: ...

Global site tag (gtag.js) - Google Analytics