3

How can I set some of the tabs in a JTabbedPane invisible? I tried using JTabbedPane#getTabComponentAt(index).setVisible(false);, but it throws a NullPointerException. I can disable the tabs, but not make them invisible.

SSCCE:

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;

public class Main {
    public static void main(String[] args) {
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setPreferredSize(new Dimension(400, 100));
        for (int i = 0; i < 7; i++)
            tabbedPane.add("tab " + i, new JLabel("content " + i));

        // this throws a NullPointerException
        tabbedPane.getTabComponentAt(1).setVisible(false);
        // this works
        tabbedPane.setEnabledAt(1, false);

        JFrame frame = new JFrame();
        frame.setContentPane(tabbedPane);
        frame.pack();
        frame.setVisible(true);
    }
}

I can not find out what I am doing wrong.

brimborium
  • 9,362
  • 9
  • 48
  • 76

1 Answers1

5

See the javadoc of the corresponding setter:

Sets the component that is responsible for rendering the title for the specified tab. A null value means JTabbedPane will render the title and/or icon for the specified tab. A non-null value means the component will render the title and JTabbedPane will not render the title and/or icon.

So the JTabbedPane#getTabComponentAt(index) method returns the Component used to render the tab if you set any, otherwise it uses a label and/or an icon.

Not sure whether you can make a tab invisible, but sure as hell you can remove them and insert them. That might be an acceptable solution

Robin
  • 36,233
  • 5
  • 47
  • 99
  • Thanks for the quick response. Ok, that doesn't seem to be the intended use for that method then... ;) I thought about remove/insert, I just thought it might be a cleaner solution to just make them invisible. But I guess I'll have to remove them. – brimborium Aug 29 '12 at 16:04
  • 1
    @brimborium I must say that the naming of those methods could be better, but to put it simply there are 2 components you can retrieve for each tab. The "content", and the "tab header". The first is retrieved using `getComponentAt` and the latter using `getTabComponentAt` – Robin Aug 29 '12 at 16:10
  • And the latter returns `null` because usually, one let's the `JTabbedPane` handle the rendering... ^^ – brimborium Aug 29 '12 at 16:17
  • @brimborium exactly. That explains why you encountered the `NullPointerException` – Robin Aug 29 '12 at 16:21
  • Sorry for the delayed accept. Thanks for your answer, it helped. – brimborium Sep 05 '12 at 10:18