5

使用本手册(http://www.comp.nus.edu.sg/~cs3283/ftp/Java/swingConnect/tech_topics/tables-trees/tables-trees.html)我正在尝试为我的项目创建树表摆动用户界面。

在我的表类的构造函数中,我重新定义了渲染,如下所示:

public class JTreeTable extends JTable {
    public JTreeTable(ITreeTableModel treeTableModel) {
        super();
        ...
        setDefaultRenderer(ITreeTableModel.class, tree); 
        ...
    }

}

其中 treeTableModel 是我的实现

interface ITreeTableModel extends TreeModel

结果表看起来接近我想要的,但我有几个问题:

在此处输入图像描述

  1. 我的代码中的字段(ID)定义为对象,但实际上它代表数字(1、2、3 等)。如何更改字段 ID 的表示?

  2. 我表中的节点不展开。但

    公共 int getChildCount(对象 parent_object_id)

返回数字 > 0

ps 我知道可能没有足够的信息来直接回答,但我至少需要一个方向来继续我的调查。

4

1 回答 1

0

Related to the first of your questions, you should implement a TreeCellRenderer. Guessing that you do would do something similar to:

//and override also all the other functions of TreeCellRenderer
public Component getTreeCellRendererComponent(JTree tree, Object value,
      boolean selected, boolean expanded, boolean leaf, int row,
      boolean hasFocus) {
    Component returnValue = null;
    if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
      Object userObject = ((DefaultMutableTreeNode) value)
          .getUserObject();
      if (userObject instanceof YourClass) {
        YourClass yourElement = (YourClass) userObject;
        if(col==0) titleLabel.setText(yourElement.getID());
        if(col==1) titleLabel.setText(yourElement.getName());
        if(col==2) titleLabel.setText(yourElement.getParentID());
        if (selected) {
          renderer.setBackground(backgroundSelectionColor);
        } else {
          renderer.setBackground(backgroundNonSelectionColor);
        }
        renderer.setEnabled(tree.isEnabled());
        returnValue = renderer;
      }
    }
    if (returnValue == null) {
      returnValue = defaultRenderer.getTreeCellRendererComponent(tree,
          value, selected, expanded, leaf, row, hasFocus);
    }
    return returnValue;
  }
}

What is currently happening to you is that your Cell Renderer is returning the Object instance element ID (DictionaryItem@11abb71 for example) instead of getting the object and call the getID() function.

You can find extra example and information on TreeCellRenderer example.

Related to your second question see the example on TreeModel example. Maybe you can also try to expand the row by code. If the "+" icon is changing to a "-" it would probably means that getChildCount is working well but what it isn't working is the getChild(int row) which will return null or an unvalid tree row element.

于 2015-06-25T08:13:25.017 回答