我必须通过将Item Object传递给面板来创建一个动态面板,它正常工作,除非我尝试更新对象值并尝试使用p.revalidate()重新绘制JPanel的内容,p.repaint( ),panel.revalidate(),panel.repaint();所以请告诉我的代码有什么问题
public class Test {
private HashMap<String,Item> collection = new HashMap<String,Item>();
public Test() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(200, 300);
frame.add(Container());
frame.repaint();
frame.setVisible(true);
}
public static void main(String args[]){
new Test();
}
private JPanel Container() {
JPanel panel = new JPanel(new MigLayout());
CreateApplicationPanels(panel,"1","A1","A2");
CreateApplicationPanels(panel,"2","B1","B2");
return panel;
}
public void CreateApplicationPanels(JPanel panel, String pid,String key1,String key2){
collection.put(pid, new Item(key1,key2));
JPanel p = new JPanel(new MigLayout("","","10[]20"));
p.add(new JLabel(collection.get(pid).getKey1()),"cell 0 0,width 30,split 3");
p.add(new JLabel(collection.get(pid).getKey2()),"cell 1 0,width 50");
p.add(new TLabel("",Theam.dark_gray),"cell 6 0, width 400");
p.setOpaque(false);
panel.add(p, String.format("cell 0 %s1,grow", pid));
p.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e){
p.setOpaque(true);
p.setBackground(Color.decode("#EAF4FF"));
}
@Override
public void mouseExited(MouseEvent e) {
p.setOpaque(false);
p.setBackground(null);
}
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
collection.get(pid).setKey1("Key1 Changes");
System.out.println(pid+"::>"+collection.get(pid).getKey1());
p.revalidate();
p.repaint();
panel.revalidate();
panel.repaint();
}
});
}
class Item{
private String key1;
private String key2;
public Item(String key1,String key2) {
setKey1(key1);
setKey2(key2);
}
public String getKey1() {
return key1;
}
public void setKey1(String key1) {
this.key1 = key1;
}
public String getKey2() {
return key2;
}
public void setKey2(String key2) {
this.key2 = key2;
}
}
}
答案 0 :(得分:1)
collection.get(pid).setKey1("Key1 Changes");
更改集合中Object的值与GUI无关。
如果您想更改标签上的文字,则需要更改标签上的文字。
label.setText("some different text");
所以诀窍是获取你想要更新的标签的引用。
我不知道你的代码在做什么。所以我不能建议一般的方法。但是您当前的代码正在更新key1值,该值分配给您添加到面板的第一个标签。
快速破解你可以做到:
JLabel label = (JLabel)p.getComponent(0);
label.setText("some different text");
您甚至不需要重新验证面板。标签将自动重绘()本身。