我有一个javax.swing.JPanel
被调用calcResPanel
(使用java.awt.GridLayout
带有1
列和不定(0
)行),它接收并显示一组BHSelectableLabel
s(扩展),它们共同表示存储在被调用javax.swing.JTextField
的 s 列表中的文本。我想我不妨给它以下行为:String
results
- 第一次,它只会添加新的
- 以下时间,它将:
results
将尽可能多的已添加标签的文本更改为尽可能多的值的文本- 如果还有未更改的标签,请删除它们,因为它们不是必需的。否则,根据需要添加尽可能多的新标签。
这对我来说很有意义。如果这个算法不是我应该做的,那么现在停止阅读并用更好的算法发布答案。但是,如果您同意,请告诉我我的代码做错了什么:
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);
这段代码的问题是它不一致地在calcResPane
. 如果您认为这个算法在概念上很好,那么请告诉我我的代码有什么问题导致它留下多余的标签?
回答
也是这么简单的回答。我觉得很聪明^^;
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);