我正在尝试渲染一个 JTree 叶以具有一个包含可编辑 JTextArea 的 JPanel,以便用户可以输入文本并能够在添加文本时向下滚动,
并且还使用包装器来限制文本的宽度,使其向下延伸以允许更多空间而不是左右滚动。
到目前为止,我已经实现了以下内容,但它看起来很奇怪,当我运行代码时,好像有两个叶子,默认的一个和渲染的。任何类型的帮助都将受到高度赞赏。
我只想知道我想做的事情是否可以实现,如果不能,我在哪里可以修改。
我不想更改图标,只更改叶子。
import java.awt.Component;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ItemEvent;
import java.util.EventObject;
import javax.swing.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
/**
*
* @author Razaractor
*/
class LeafRenderer extends AbstractCellEditor implements
TreeCellRenderer, TreeCellEditor {
//Text area to be place on JPanel
JTextArea text = new JTextArea();
DefaultTreeCellRenderer nonLeafRenderer = new DefaultTreeCellRenderer();
@Override
public Object getCellEditorValue() {
return text.getText();
}
@Override
public boolean isCellEditable(final EventObject event) {
return true;
}
@Override
public Component getTreeCellRendererComponent(
final JTree tree, final Object value,
final boolean selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus) {
//Default leaf
Component render = nonLeafRenderer.getTreeCellRendererComponent(tree,
value, selected, expanded, leaf, row, hasFocus);
if (selected && leaf) {
final JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.X_AXIS);
panel.setLayout(layout);
text.setColumns(20);
text.setLineWrap(true);
text.setRows(5);
text.setWrapStyleWord(true);
text = new JTextArea(String.valueOf(value));
text.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
panel.setSize(panel.getPreferredSize());
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
JScrollPane scroll = new JScrollPane(text);
panel.add(scroll);
render = panel;
return panel;
}
return render;
}
@Override
public Component getTreeCellEditorComponent(
final JTree tree,
final Object value,
final boolean isSelected,
final boolean expanded,
final boolean leaf,
final int row) {
Component editor = nonLeafRenderer.getTreeCellRendererComponent(tree,
value, true, expanded, leaf, row, true);
final JPanel p = new JPanel();
if (editor instanceof JPanel) {
editor = (JPanel) editor;
}
return editor;
}
public void itemStateChanged(ItemEvent itemEvent) {
if (stopCellEditing()) {
fireEditingStopped();
}
}
}