问题
I have a custom JTree implementation that implemts convertValueToText
. This implementation depends on some global state. If the returned string is longer (actually I think wider as in pixels triggers it) than a previously returned string, the text will be truncated and padded with "...". This is true when the redrawing is caused by (de)selecting the element or a repaint
on the tree.
Is it valid to implement convertValueToText
in such a way? (I recognize that the tree display will not automatically be updated).
How can I get rid of the "..." and force all elements to be correctly drawn with their current textual value?
Update2:
Appearently I violated Swings rather strict treading policy (http://docs.oracle.com/javase/6/docs/api/javax/swing/package-summary.html). Doing the update with:
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
for (int row = 0; row < tree.getRowCount(); row++) {
((DefaultTreeModel) tree.getModel())
.nodeChanged((TreeNode) tree.getPathForRow(row)
.getLastPathComponent());
}
}
});
appears to work correctly.
Update:
Here is a minimal example:
import java.util.Enumeration;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
public class WeirdTreeFrame extends JFrame {
public class WeirdTree extends JTree {
public WeirdTree(TreeNode root) {
super(root);
}
@Override
public String convertValueToText(Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
return super.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
}
}
public class WeirdNode implements TreeNode {
protected WeirdNode parent;
protected WeirdNode children[];
protected int dephth;
protected String name;
protected String names[] = {"Foo", "Bar", "Ohh"};
public long superCrazyNumber;
public WeirdNode(WeirdNode parent, String name) {
this.parent = parent;
this.name = name;
if (parent != null) {
dephth = parent.dephth + 1;
} else {
dephth = 0;
}
if (dephth < 10) {
children = new WeirdNode[3];
for (int i = 0; i < 3; i++) {
children[i] = new WeirdNode(this, name + names[i]);
}
}
}
@Override
public TreeNode getChildAt(int childIndex) {
if (childIndex >= getChildCount()) return null;
return children[childIndex];
}
@Override
public int getChildCount() {
return (children != null) ? children.length : 0;
}
@Override
public TreeNode getParent() {
return parent;
}
@Override
public int getIndex(TreeNode node) {
for (int i = 0; i < children.length; i++) {
if (children[i] == node) return i;
}
throw new RuntimeException();
}
@Override
public boolean getAllowsChildren() {
return true;
}
@Override
public boolean isLeaf() {
return getChildCount() == 0;
}
@Override
public Enumeration children() {
return new Enumeration<TreeNode>() {
int nextIdx = 0;
@Override
public boolean hasMoreElements() {
return nextIdx < getChildCount();
}
@Override
public TreeNode nextElement() {
return getChildAt(nextIdx++);
}
};
}
@Override
public String toString() {
return "[" + dephth + "]" + name + "@" + superCrazyNumber;
}
}
public WeirdNode root;
private WeirdTree tree;
public WeirdTreeFrame() {
root = new WeirdNode(null, "Blubb");
tree = new WeirdTree(root);
add(tree);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
}
public void update() {
for (int row = 0; row < tree.getRowCount(); row++) {
((DefaultTreeModel) tree.getModel()).nodeChanged((TreeNode)tree.getPathForRow(row).getLastPathComponent());
}
}
public static void main(String[] args) {
WeirdTreeFrame frame = new WeirdTreeFrame();
Random rnd = new Random(41);
for (long i = 0; ; i++) {
for (WeirdNode node = frame.root; node != null; node = (WeirdNode)node.getChildAt(rnd.nextInt(3))) {
node.superCrazyNumber++;
}
if (i % 1e7 == 0) {
System.out.println("Update: " + i);
frame.update();
}
}
}
}
With the update()
method I tried to fire the appropriate events to make sure all visible nodes are updated correctly. As you can see some computation is happening in parallel and perioically during the computation I want to update the tree labels (NOT the structure).
The issue with the update()
method is that some nodes are labled completely wrong as you can see in the attached picture (should be "[0]..." for root node, "[n].."for nth level)
I assume this is some race condition.
回答1:
This probably means your are updating the tree without telling it you changed something so when it redraws it just redraws it without recalculating the layout. You have to call DefaultTreeModel.nodeChanged(node) from the model to notify JTree you actually modified something then it will handle recalculating the size of the node. Or use the proper TreeModelListener interface call to notify the Tree something has changed. If you do that it will relayout that node properly.
If you are properly notifying the tree JLabel is redrawing itself, but it is not performing layout again to calculate how much space it needs for the new string. If you revalidate() it (as opposed to repaint()) it should perform layout again and it will calculate its preferred size again based on the new string and resize itself to surround the entire string.
The section in the main() method that manipulates the tree then calls update is violating the swing thread rule because when WeirdFrame is constructed it is realized by the call setVisible(). That means you can't touch it or any model being used to draw from from any thread except the Swing Event Dispatcher thread. It doesn't have anything to do with whether you implement TreeNode or not.
The easiest fix to this is to defer it back to the Event Dispatch thread. like so:
public void update( final WeirdNode node, final long nextSuperCrazyNumber ) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
node.superCrazyNumber = nextSuperCrazyNumber;
((DefaultTreeModel) tree.getModel()).nodeChanged(node);
}
});
}
public static void main(String[] args) {
WeirdTreeFrame frame = new WeirdTreeFrame();
Random rnd = new Random(41);
for (long i = 0; ; i++) {
for (WeirdNode node = frame.root; node != null; node =(WeirdNode)node.getChildAt(rnd.nextInt(3))) {
long superCrazyNumber = node.superCrazyNumber;
frame.update( node, superCrazyNumber++ );
}
}
}
Now notice how the main thread is running unfettered, but it isn't directly manipulating the data contained in the WeirdNode. Remember WeirdNode's toString() method is called to render a string to display so it's being called on the SwingThread. If you write to WeirdNode.superCrazyNumber on from another thread you are violating the threading rule. The main thread getting a copy doing some calculation to it, then posting the update back to the Swing Thread using SwingUtilities.invokeLater() NOT invokeAndWait(). You don't need invokeAndWait except is very limited situations, and it has to potential to cause lock ups so its best to just avoid it. Your UI doesn't have to reflect the model at every second it just has to eventually reflect it and so invokeLater is your friend. The key thing here is I'm not doing a write operation on the main thread as the code before, and I certainly can call update on the individual nodes without having to resort to shotgun updates.
回答2:
After changing the node call method nodeChanged.
((DefaultTreeModel)tree).getModel().nodeChanged(node);
回答3:
The DefaultTreeCellRenderer
is a JLabel
, which adds the ellipses as a convenience. You can see the effect by resizing the frame in this example. Several alternatives are possible:
Use a suitable layout for the enclosing container; the example uses
GridLayout
.Use a component for the renderer, such as
JTextField
, that can scroll horizontally.Add a
TreeSelectionListener
that updates an adjacent text component.
来源:https://stackoverflow.com/questions/10374161/jtree-convertvaluetotext-return-is-truncated-when-with-changed