Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JScrollPane component change

i have a JScrollPane. But default it displays JTextArea.

JTextArea jTextArea = new JTextArea();
JScrollPane pane = new JScrollPane(jTextArea);

so here everything is fine. But now i would like to change JScrollPane component by user action:

pane.remove(jTextArea);
pane.add(new JTable(data[][], columns[]));
pane.revalidate();
frame.repaint();

frame in my main Window. JScrollPane is added to main window with GridBagLayout. But this doesn't work. After running action JScrollPane becomes grey.

like image 740
Ruslan Avatar asked Mar 02 '26 20:03

Ruslan


2 Answers

jScrollPane.getViewport().remove/add
like image 162
StanislavL Avatar answered Mar 04 '26 10:03

StanislavL


One alternative is to put a JPanel with a CardLayout1 into the JScrollPane, add both the components to the panel, then simply flip between the text area and table as needed.

  1. How to Use CardLayout

Given the components might be of vastly different size, it might be better to do it this way:

JPanel with CardLayout contains many JScrollPane instances, each of which contains a single component. That will also work inherently better for a JTable.

like image 20
Andrew Thompson Avatar answered Mar 04 '26 09:03

Andrew Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!