好的,我在 Swing 中找不到一个像样的示例来使用比基本功能更多的自定义 TreeModel,所以我编写了自己的(代码如下),所以我可以询问有关它的问题,而不是询问更复杂的应用程序当我了解如何编写它时,这就是我真正想写的。抱歉,这里有多个相关问题,很难在没有示例的情况下在真空中问这些 Q,我认为最好在一篇文章中提出示例,而不是分开我的问题。我的真实应用程序不是无限的,只是很大(存储在数据库中的状态),因此自定义 TreeModel 似乎很合适。
package com.example.test.gui;
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.MouseEvent;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
/*
* GUI rendering of the ancestry of hailstone numbers
* (see http://mathworld.wolfram.com/CollatzProblem.html)
*
* This is an infinite tree model.
*
* each node in the tree is a Long number
* each node has 1 or 2 children:
* all nodes N have a child 2N
* any node N = 3k+1, where k > 0, has a second child k
*
* checkboxes are present just to see custom rendering
* - nodes N where N is divisible by 7 are editable, the rest are not
* - editable nodes override their default state (stored in a hashmap)
* - default state of a node N is checked if N is divisible by 5,
* unchecked otherwise
*/
class HailstoneTreeModel implements TreeModel {
final private Map<Long,Boolean> modifiedCheckState = new HashMap<Long,Boolean>();
@Override public Object getChild(Object parent, int index) {
if (!(parent instanceof Long))
return null;
if (index < 0 || index > 1)
return null;
final long l = ((Long)parent).longValue();
if (index == 0)
{
return (l*2);
}
else if ((l > 1) && (l-1)%3 == 0)
{
return (l-1)/3;
}
else
return null;
}
@Override public int getChildCount(Object parent) {
if (!(parent instanceof Long))
return 0;
final long l = ((Long)parent).longValue();
if ((l > 1) && (l-1) % 3 == 0)
return 2;
return 1;
}
@Override public int getIndexOfChild(Object parent, Object child) {
if (parent instanceof Long && child instanceof Long)
{
final long p = ((Long)parent).longValue();
final long c = ((Long)child).longValue();
if (p*2 == c)
return 0;
if (p == 3*c+1)
return 1;
}
return -1;
}
@Override public Object getRoot() {
return 1L;
}
@Override public boolean isLeaf(Object arg0) {
return false;
}
@Override
public void addTreeModelListener(TreeModelListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void removeTreeModelListener(TreeModelListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void valueForPathChanged(TreePath arg0, Object arg1) {
// !!! what is typically done here and when does this get called?
}
public boolean isEditable(TreePath path) {
if (path != null) {
Object node = path.getLastPathComponent();
// only the nodes divisible by 7 are editable
if (node instanceof Long)
{
return ((Long)node) % 7 == 0;
}
}
return false;
}
private void _setState(Long value, boolean selected)
{
this.modifiedCheckState.put(value, selected);
System.out.println(value+" -> "+selected);
}
public void setState(Object value, boolean selected) {
if (value instanceof Long)
{
_setState((Long)value, selected);
}
}
private boolean _getState(Long value)
{
Boolean b = this.modifiedCheckState.get(value);
if (b != null)
{
return b.booleanValue();
}
return (value.longValue() % 5 == 0);
}
public boolean getState(Object value)
{
if (value instanceof Long)
{
return _getState((Long) value);
}
return false;
}
public void toggleState(Object value) {
if (value instanceof Long)
{
_setState((Long)value, !_getState((Long)value));
}
}
}
// adapted from http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxNodeTreeSample.htm
class CheckBoxNodeRenderer implements TreeCellRenderer {
final private JCheckBox nodeRenderer = new JCheckBox();
final private HailstoneTreeModel model;
private Long currentValue = null; // value currently being displayed/edited
final private Color selectionBorderColor, selectionForeground, selectionBackground,
textForeground, textBackground;
protected JCheckBox getNodeRenderer() {
return this.nodeRenderer;
}
public CheckBoxNodeRenderer(HailstoneTreeModel model) {
this.model=model;
Font fontValue;
fontValue = UIManager.getFont("Tree.font");
if (fontValue != null) {
this.nodeRenderer.setFont(fontValue);
}
Boolean booleanValue = (Boolean) UIManager
.get("Tree.drawsFocusBorderAroundIcon");
this.nodeRenderer.setFocusPainted((booleanValue != null)
&& (booleanValue.booleanValue()));
this.selectionBorderColor = UIManager.getColor("Tree.selectionBorderColor");
this.selectionForeground = UIManager.getColor("Tree.selectionForeground");
this.selectionBackground = UIManager.getColor("Tree.selectionBackground");
this.textForeground = UIManager.getColor("Tree.textForeground");
this.textBackground = UIManager.getColor("Tree.textBackground");
}
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
Component returnValue = this.nodeRenderer;
String stringValue = tree.convertValueToText(value, selected,
expanded, leaf, row, false);
this.nodeRenderer.setText(stringValue);
this.nodeRenderer.setSelected(false);
this.nodeRenderer.setEnabled(tree.isEnabled());
if (selected) {
this.nodeRenderer.setForeground(this.selectionForeground);
this.nodeRenderer.setBackground(this.selectionBackground);
} else {
this.nodeRenderer.setForeground(this.textForeground);
this.nodeRenderer.setBackground(this.textBackground);
}
if (value instanceof Long)
{
this.currentValue = (Long) value;
}
this.nodeRenderer.setSelected(this.model.getState(value));
returnValue = this.nodeRenderer;
return returnValue;
}
public Long getCurrentValue() { return this.currentValue; }
}
class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {
final CheckBoxNodeRenderer renderer;
final HailstoneTreeModel model;
public CheckBoxNodeEditor(HailstoneTreeModel model) {
this.model = model;
this.renderer = new CheckBoxNodeRenderer(model);
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
Object cb = itemEvent.getItem();
if (cb instanceof JCheckBox && itemEvent.getStateChange() == ItemEvent.SELECTED)
{
Long v = CheckBoxNodeEditor.this.renderer.getCurrentValue();
CheckBoxNodeEditor.this.model.toggleState(v);
}
// !!! the following 3 lines are important because... ?
if (stopCellEditing()) {
fireEditingStopped();
}
}
};
this.renderer.getNodeRenderer().addItemListener(itemListener);
}
public Object getCellEditorValue() {
JCheckBox checkbox = this.renderer.getNodeRenderer();
return checkbox;
}
@Override public boolean isCellEditable(EventObject event) {
boolean returnValue = false;
Object source = event.getSource();
if (event instanceof MouseEvent && source instanceof JTree) {
MouseEvent mouseEvent = (MouseEvent) event;
TreePath path = ((JTree)source).getPathForLocation(mouseEvent.getX(),
mouseEvent.getY());
returnValue = this.model.isEditable(path);
}
return returnValue;
}
public Component getTreeCellEditorComponent(JTree tree, final Object value,
boolean selected, boolean expanded, boolean leaf, int row) {
Component editor = this.renderer.getTreeCellRendererComponent(tree, value,
true, expanded, leaf, row, true);
return editor;
}
}
public class VirtualTree1 {
public static void main(String[] args) {
HailstoneTreeModel model = new HailstoneTreeModel();
// Create a JTree and tell it to display our model
JTree tree = new JTree(model);
tree.setCellRenderer(new CheckBoxNodeRenderer(model));
tree.setCellEditor(new CheckBoxNodeEditor(model));
tree.setEditable(true);
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tree);
// Display it all in a window and make the window appear
JFrame frame = new JFrame("Hailstone Tree Demo");
frame.getContentPane().add(scrollpane, "Center");
frame.setSize(400,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
有关显示的内容,请参见第一条评论(应该在上方可见)。这是一个显示无限树的自定义 TreeModel,这在“常规”树中是不可能的,其中树中的所有节点都需要实际存在于内存中,但可以使用自定义 TreeModel,因为唯一显示/实例化的部分是用户点击的那些,本质上是有限的。:-)
我有几个杂项问题。将为我的问题 #4 提供可接受的答案,以获得最佳答案。
1) TreeModel 侦听器——我是否正确假设这是用于希望从我的 TreeModel 接收更新事件的类?(无论是我写的还是其他人写的)典型的用例是什么?
2) TreeModel.valueForPathChanged()
-- 什么时候调用它,我通常会怎么做?
3)(这与 TreeCellEditor / TreeCellRenderer 有关)——我改编的示例中的行有以下调用:
if (stopCellEditing()) {
fireEditingStopped();
}
这是用来干嘛的?
4)就班级组织而言——有没有更好的方法来组织这种事情?我想我应该在 TreeModel(M = MVC 中的模型)和 TreeCellEditor / TreeCellRenderer(V = 视图或 C = 控制器,我不确定)之间进行分离,但他们隐约需要相互了解,并且我不确定哪个应该包含对哪个的引用。现在我将 TreeModel 作为一个独立的对象,并且编辑器/渲染器具有对 TreeModel 的引用,因此它可以根据需要查询/改变模型。另外我想知道自定义 TreeCellEditor 和 TreeCellRenderer 是否真的应该是一个实现这两个接口的类。我的itemStateChanged()
方法在CheckBoxNodeEditor
看起来有点奇怪......当复选框被点击时我得到一个项目监听器事件,然后我假设这个事件来自渲染器,并切换适当的值,因为我似乎无法弄清楚如何确定是否复选框目前被选中或未选中,此复选框对象中的选择似乎是鼠标是否已单击或松开,而不是复选框状态。
可能有不止一种方法可以重组它,所以它似乎是一种更好、更模块化的方法,但现在我不确定如何做到这一点,所以任何建议都值得赞赏。
5) 显示为树层次结构的有向无环图 (DAG) -- 如果您运行应用程序,然后展开节点 1、2、4、8、16、32、64、128,您将看到第二个“1”,即实际上与第一个“1”相同的节点,因为此示例应用程序中的节点值只是Long
对象。如果将第二个“1”扩展为 1,2,4,8,16,32,64,128,您现在将看到两个“21”节点。可以根据需要选中/取消选中“21”节点。但在理想情况下,当我单击其中一个时,两个“21”都会更新它们的选中状态。有没有办法自动做到这一点?或者我是否必须跟踪当前同时显示的单个节点的所有多个路径?(或者,存在的单个节点的所有路径 - 在有限 DAG 中可能,在无限 DAG 中不可能)这只是 DAG 的问题,其中有多个路径可以到达同一个节点......我必须在我的应用程序中处理这个问题。