我尝试使用自定义 TreeRenderer 制作 JTree
public class TextCellRender implements TreeCellRenderer {
JPanel panel;
JTextArea text;
JLabel label;
LayoutManager Layout;
public TextCellRender() {
text = new JTextArea();
text.setWrapStyleWord(true);
text.setLineWrap(true);
text.setSize(360, text.getPreferredSize().height);
label = new JLabel();
panel = new JPanel();
panel.add(label);
panel.add(text);
}
@Override
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 FieldObj)) {
FieldObj my = (FieldObj) userObject;
String fieldText = "";
text.setText(my.valueList);
label.setText(my.FieldName);
}
return panel;
}
return returnValue;
}
}
并使用自定义编辑器
public class TextCellEdit extends AbstractCellEditor implements TreeCellEditor {
其中 getTreeCellEditorComponent 将面板返回为 getTreeCellEditorComponent 但使用 JComboBox 从数据库填充项目。渲染和编辑器工作得很好我可以点击字段和组合框显示来自 db 的值。
public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean isSelected, boolean expanded, boolean leaf, int row) {
if (value != null && value instanceof DefaultMutableTreeNode) {
Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
if (userObject instanceof FieldObj) {
FieldObj my = (FieldObj) userObject;
box.removeAllItems();
label.setText(my.FieldName);
populatebox(my.FieldName);
box.addItem(my.valueList);
panel.add(label);
panel.add(box);
} else {
box.addItem("Uknown object type");
}
return panel;
}
}
public Object getCellEditorValue() {
System.out.println("getCellEditoValue returns :" + box.getSelectedItem());
return box.getSelectedItem();
}
但它没有保存在渲染 textArea 我的意思是在渲染中我有面板:
JLabel (FieldName)
JTextArea (FieldValue)
当我点击 JTextArea 我有我的编辑器,它有:
JLabel (FieldName)
JComboBox(FieldValues which I have paid from db)
但是当我从 Edit ComboBox 中选择某些内容时,它不会保存在 Render TextArea 中所以问题是这些东西应该如何工作?
渲染组件如何从 Edit 组件中获取价值?