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).
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();
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With