简体   繁体   English

在Java Swing中刷新JPanel

[英]Refresh JPanel in Java Swing

Let's suppose I've a list of String like this 假设我有一个像这样的String列表

List<String> button_names={"Button1","Button2","Button3","Button4"};

I've to insert JButtons with those texts in a JPanel so I do 我必须在JPanel中将带有这些文本的JButtons插入,所以

for (int i=0; i<button_names.length; i++)
   myJPanel.add(new JButton(button_name[i]));

My question is... If my model (in this case, my List button_names) changes for any reasons, how can I refresh my JPanel in order to show that change? 我的问题是...如果我的模型(在这种情况下,我的列表button_names)由于任何原因发生了变化,如何刷新我的JPanel以显示该变化? Should I do 我应该做

myJPanel.removeAll()

and insert again my JButtons()? 并再次插入我的JButtons()? Thank you in adance 谢谢你

Yes removeAll and then reinserting new buttons is the easiest and generally the best way to go. 是的,removeAll,然后重新插入新按钮是最简单的方法,通常也是最好的方法。 Otherwise, you have to start figuring out which buttons have been removed, which have been added, and where in the list these new buttons are. 否则,您必须开始确定哪些按钮已被删除,哪些按钮已添加以及这些新按钮在列表中的位置。 Also, buttons in the list should change position I guess, so you'd have to cover that case to. 另外,我猜列表中的按钮应该会改变位置,因此您必须将这种情况包括在内。

You can write a method like this that you could use in initial creation, and when you want to reload the list 您可以编写这样的方法,以便在初始创建以及要重新加载列表时使用

void addButtonsToPanel(JPanel p) {
  p.removeAll();
  for (int i=0; i<button_names.length; i++)
   myJPanel.add(new JButton(button_name[i]));
  validate();
  repaint();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM