在java中向运行时上的面板添加元素
可能重复:在java中向运行时上的面板添加元素,java,swing,layout,constructor,jpanel,Java,Swing,Layout,Constructor,Jpanel,可能重复: 我已经创建了一个面板,并使用了gridlayout publicpnlfriends(){ 初始化组件(); 这个.setLayout(新的GridLayout(10,1)); //showFriends(); } 私有void formComponentShowed(java.awt.event.ComponentEvent evt){ showFriends(); 系统输出打印(“comp”); } 私人朋友() { //整数id=NewMain.network.getEdge
我已经创建了一个面板,并使用了gridlayout
publicpnlfriends(){
初始化组件();
这个.setLayout(新的GridLayout(10,1));
//showFriends();
}
私有void formComponentShowed(java.awt.event.ComponentEvent evt){
showFriends();
系统输出打印(“comp”);
}
私人朋友()
{
//整数id=NewMain.network.getEdges().get(Main.uuid.getDegree();
对于(int i=0;i<10;i++)
{
String name=“as”;
字符串占用=“adf”;
字符串place=“asdf”;
整数连接=5;
添加(displayMiniProfile(姓名、职业、地点、连接));
}
}
其中,displayMiniProfile
返回一个JPanel
现在,当我在父JPanel的构造函数中调用这个函数时,它就可以工作了,我可以添加MiniProfile JPanel
但是,当我在componentShowed
事件的响应中调用此函数时,它不会显示任何内容
为什么?
我怎样才能做到这一点呢?没有显示任何内容,因为添加新面板后,
JPanel
仍然没有得到验证。你需要打电话
revalidate();
repaint();
打完电话
this.add(displayMiniProfile(name,occupation,place,connections));
你没有向天空中伟大的编码神祈祷?…如果没有一个密码,一切都将是猜测工作…它工作了。我只想再问一件事。重新绘制有效吗?不,你需要在这里进行重新验证,
repaint
不会对新添加的面板进行必要的验证:)@Reimeus它实际上是revalidate()
和repaint()
,以反映更改,在某些情况下,只调用revalidate
是行不通的。在这种情况下,repaint()
并不是严格需要的,但已经添加了它,作为未来读者的“最佳实践”。
this.add(displayMiniProfile(name,occupation,place,connections));