How do I create a JScrollPane within a JTabbedPane?

830 views Asked by At

I am trying to create a JScrollPane within one of the tabs to my JTabbedPane. I tried what I though would work which was this:

    pane.add("Main", mainGame);// These are my other tabs
    pane.add("Upgrades", upgradeScreen); //the JTabbedPane
    pane.add("Credits", creditsTab);
    upgradeScreen.setLayout(null); //The null layout
    lblMoney2.setBounds(10, 11, 277, 22);
    upgradeScreen.add(lblMoney2); // A simple JLabel
    scrollPane.add(upgradeScreen); //my JScrollPane

Where pane is my JTabbedPane and scrollPane is my JScrollPane. This simply got rid of my upgradesScreen tab. I kind of expected this but I did not know what else to do. If more code is needed for you to figure it out, tell me and i'll put it in, otherwise, thanks for the help!

2

There are 2 answers

2
MadProgrammer On

Don't us JScrollPane#add, instead you want to use JScrollPane#setViewportView

Check out How to use ScrollPane more details.

Advise- Don't use null layouts, they limit the ability for your application to run on multiple platforms. Instead take the time to learn how layout managers work

0
Sage On

This simply got rid of my upgradesScreen tab.'

yes, because no component can have two parents at once. You added upgradeScreen to JTabbedPane first and then again added it to a JScrollPane. The Component's add(component) function will eventually call the addImpl(component) function: which will remove the component from it's old parent and add it to the new parent.

However:

  1. You need to add the JScrollPane to the JTabbedPane instance.
  2. The component which you wish to scroll set it as a view to JScrollPane using the setViewportView(component) function. for your context it is the upgradeScreen