我正在使用带有一些 JLabels 和 JTextFields 的 JPanel 作为 JTree 中的编辑器和渲染器。
用户可以单击任何 JTextField 并修改文本。一切正常。
我所缺少的是如何在用户键入时动态调整(增长)JTextField 的大小。
下面是一个说明问题的小示例程序。单击即“颜色”并输入一些附加字符。JTextField 保持其大小,这是预期的,但我希望它能够增长和缩小以适应文本。
我尝试了不同的布局管理器,计算 JTextField 和 JPanel 的首选大小,调用 invalidate() 和 JPanel 和 Tree 等等,但没有成功。
有任何想法吗?
import java.awt.Component;
import java.util.EventObject;
import javax.swing.AbstractCellEditor;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
public class Tree {
public static void main(final String[] args) {
new Tree().grow();
}
private void grow() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTree tree = new JTree();
tree.setEditable(true);
tree.setCellRenderer(new SomeTreeCellRenderer());
tree.setCellEditor(new SomeTreeCellRenderer());
frame.add(new JScrollPane(tree));
frame.pack();
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class SomeTreeCellRenderer extends AbstractCellEditor implements
TreeCellRenderer, TreeCellEditor {
@Override
public Object getCellEditorValue() {
return null;
}
@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) {
final JPanel panel = new JPanel();
final BoxLayout layout = new BoxLayout(panel, BoxLayout.X_AXIS);
panel.setLayout(layout);
panel.add(new JLabel("Some text: "));
panel.add(new JTextArea(String.valueOf(value)));
return panel;
}
@Override
public Component getTreeCellEditorComponent(
final JTree tree, final Object value, final boolean isSelected,
final boolean expanded, final boolean leaf, final int row) {
return getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, false);
}
}
}