Reusing of components in Java not properly trimming un-reused ones
I have a javax.swing.JPanel
called calcResPanel
(using a java.awt.GridLayout
with 1
column and indefinite (0
) rows) which is to receive and display a set of BHSelectableLabel
s (which extend javax.swing.JTextField
) with collectively represent the text stored in the list of String
s called results
. I figured that I might as well give it the following behavior:
- The first time, it will only add new ones
- Following times, it will:
- Change the text of as many labels that are already added as possible to be that of as many of the values in
results
as possible - If there are any labels left that haven't been changed, remove those, as they are not necessary. Else, add as many new labels as needed.
- Change the text of as many labels that are already added as possible to be that of as many of the values in
This makes sense to me. If this alg开发者_如何学编程orithm is not what I should be doing, then stop reading now and post an answer with a better algorithm. However, if you agree, then tell me what I've done wrong with my code:
int i, r, l;
for (i=0, r = results.length(), l = calcResPanel.getComponentCount(); i < r; i++)
if (i < l)
((BHSelectableLabel)calcResPanel.getComponent(i)).setText(results.get(i));
else
calcResPanel.add(new BHSelectableLabel(results.get(i)));
for (;i < l; i++)//If there are excess, unused lables, remove them
calcResPanel.remove(i);
The problem with this code is that it inconsistently leaves excess labels in calcResPane
. If you think this algorithm is good in concept, then please tell me what is wrong with my code that makes it leave excess labels?
Answer
Such a simple answer, too. I feel SO smart ^^;
int i, r, l;
for (i=0, r = results.length(), l = calcResPanel.getComponentCount(); i < r; i++)
if (i < l)
((BHSelectableLabel)calcResPanel.getComponent(i)).setText(results.get(i));
else
calcResPanel.add(new BHSelectableLabel(results.get(i)));
for (;i < l; i++)//If there are excess, unused lables, remove them
calcResPanel.remove(r);
for (;i < l; i++)//If there are excess, unused lables, remove them
calcResPanel.remove(i);
You can never do a remove like that because you skip every 2nd item. Lets say you have 5 items and you try to delete them all:
The first time through the loop i = 0, so you remove item 0 and you are left with 1, 2, 3, 4.
Next time throught the loop i = 1, so you remove item 2 and you are left with 1, 3, 4.
I hope you get the pattern.
The solution is to remove items from the end, one at a time.
精彩评论