Question

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 BHSelectableLabels (which extend javax.swing.JTextField) with collectively represent the text stored in the list of Strings called results. I figured that I might as well give it the following behavior:

  1. The first time, it will only add new ones
  2. Following times, it will:
    1. 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
    2. 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.

This 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?

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);
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top