Java - 替换 JFrame 中的组件 [英] Java - replace compoment in JFrame
问题描述
我正在努力使用 Java GUI - 提前感谢您的任何帮助!我有一个 JFrame,其中有几个组件:button (Jbutton) 触发动作侦听器,comp 这是我试图替换 JScrollPane的组件strong> 里面有一个组件(不管是什么类型的组件,可以是文本字段、表格或任何东西).
I am struggling with java GUI - thanks for any help in advance! I have a JFrame in which I have several components: button (Jbutton) that triggers action listener, comp which is a component Im trying to replace a JScrollPane with a component in it (it doesnt matter what type of component, could be text field, table or anything).
我想触发一个操作 - 删除组件,在删除组件的同一位置放置一个新组件并重新绘制窗口(我使用它来显示不同类型的文本字段和 JTables).这就是我所拥有的:
I would like to trigger an action - delete the component, place a new one on the same place as the deleted one and repaint the window (I am using this to show different types of text fields and JTables). This is what I have:
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 的内容,它会刷新但它仍然显示旧的).
Why doesnt function replace work? It doesnt do anything (it changes the component in logic so if I access the content of comp, it is refreshed but it still shows the old one).
我写的有点象征性,因为我的代码很长...感谢您的帮助!忘记了我的代码中的一行..
I wrote it kinda symbolic, cause my code is very long... Thanks for any help! edit: forgot one line in my code..
推荐答案
您不必像之前那样尝试移除滚动窗格.
It's not necessary for you to try to remove the scroll pane as you did.
要更改滚动窗格显示的组件,只需进行以下调用:
To change the component shown by the scroll pane simply make this call:
sp.setViewportView(new Component(...));
在该调用之后,旧组件从视图中移除并替换为新组件.
after that call, the old component is removed from view and replaced by the new component.
所以你的代码应该看起来像这样:
So your code should look somewhat like this:
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);
}
这篇关于Java - 替换 JFrame 中的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!