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:
results
as possibleThis makes sense to me. If this algorithm 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?
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.