Java - 在JFrame中替换组件

4
我正在努力学习Java GUI,感谢您提前的任何帮助!我有一个JFrame窗口,在其中有几个组件:触发动作监听器的按钮(JButton),一个组件(comp),我正在尝试使用一个组件替换其中的JScrollPane(无论是文本框、表格还是其他类型都可以)。
我想触发一个动作,删除该组件,将一个新组件放置在与已删除组件相同的位置,并重新绘制窗口(我正在使用此功能来显示不同类型的文本框和JTable)。这是我的代码:
JScrollPane sp = new JScrollPane(comp);
this.add(sp, BorderLayout.CENTER);
//this works so far - first time I display this is ok!

private void replace() {
 comp = new Component(...); //name and type of the components is not important
 sp = new JSCrollPane(comp);
 this.remove(sp); //remove old component
 add(sp, BorderLayout.CENTER);
 repaint();
 revalidate();
}

为什么函数替换不起作用?它没有任何作用(它会更改逻辑中的组件,因此如果我访问comp内容,则会刷新,但仍然显示旧内容)。
我写的代码有点象征性,因为我的代码很长...感谢任何帮助!编辑:我忘记了代码中的一行...
3个回答

6

您不必像之前那样尝试移除滚动窗格。

要更改滚动窗格显示的组件,只需进行以下调用:

sp.setViewportView(new Component(...));

在那个调用之后,旧组件将被从视图中移除并被新组件所替代。

因此,你的代码应该类似于这样:

JScrollPane sp = new JScrollPane(comp);
this.add(sp, BorderLayout.CENTER);

private void replace() {
    comp = new Component(...); //name and type of the components is not important
    sp.setViewportView(comp);
}

2

从您的代码来看,您添加的第一个滚动窗格(this.add)与您删除的滚动窗格(this.remove)不同。测试从remove返回的布尔值,以查看它是否已实际删除。我认为您会发现它并没有被删除。


这就是错误所在,我本应该先删除 sp,然后再创建并重新添加它... - Smajl

1

这个 IT 相关问题有一个解决方案:此板块

jpanel.remove(component); //remove component from your jpanel in this case i used jpanel 
jpanel.revalidate(); 
jframe.repaint();//repaint a JFrame jframe in this case 

to add: 
jpanel.add(component); //add component to jpanel in this case i used jpanel 
jpanel.revalidate(); 
jframe.repaint();//repaint a JFrame jframe in this case 

看看这个对你有没有用。我自己还没试过...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接