I need to know the size of a JPanel
when I add it to a JTabbedPane
to compute other values. If I call the add(Component)
method, when does the Component
get its size?
For example,
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel();
panel.setBackGround(Color.RED); // pretty colors!
tabbedPane.add(panel);
int newTabIndex = tabbedPane.indexOfComponent(panel);
tabbedPane.setSelectedIndex(newTabIndex);
Thank you in advance!
Edit @mKorbel suggested setting the visibility of the JPanel to true:
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel();
panel.setBackGround(Color.RED);
tabbedPane.add(panel);
panel.setVisible(true); // NEW LINE
int newTabIndex = tabbedPane.indexOfComponent(panel);
tabbedPane.setSelectedIndex(newTabIndex);
Unfortunately, when I applied this change to my own program, the JPanel
still had a width and height of 0 and 0, respectively. What else can I try?
after
JFrame.pack()
(not your issue)isVisible()
is already true (your issue) in the GUIJTabbedPane
won't be sized until it is attached to a container that is capable of laying it out.Window#pack
s job is to determine the preferred size of the child components and size them based on the requirements of the layout manager.Only at this time would a component (and your
JTabbedPane
) be sized.Components may be resized in response to changes in the container hierarchy as well, but the basic process is the same. The
JTabbedPane
s parent container will decide when it needs to update it's contents and perform a new layout operation, resizing the components based on it's needsNone of your examples show the tabbed pane been added to a parent container...
Updated with simple test...
The following example basically demonstrates when a component would be resized.
Output...
As you can see from the output, until the frame is
packed
, nothing is sizedJTabbedPane's size is determined by the size of the largest component that's added into it. In your case, the size of the JPanel must be set using JPanel.setPreferredSize() method. This will ensure that JPanel gets rendered properly