JTabbedPane.getTabComponentAt(int) returning null

折月煮酒 提交于 2019-12-10 14:47:25

问题


I have the following code :

JTabbedPane container;
...
AWindow page = WinUtils.buildWindow();
boolean existing = checkIfExists(page); // in this code, this will always be false
if(!existing)
{
    String tabName = page.getLoadedFileLocation().getName();
    container.addTab(page.getLoadedFileLocation().getName(), page);
}
Component comp = container.getTabComponentAt(0);
int sel = container.getSelectedIndex();
container.setSelectedComponent(page);

the thing is :

container.getTabComponentAt(0)

returns null. The other weird thing is :

container.getSelectedIndex()

returns 0. The logical thing that I think should happen, is to have a reference to the created window. Why am I receiving null? What am I doing wrong?


回答1:


getTabComponentAt() returns the custom component you might add as the tab title. You might be looking for the getComponentAt() method to return the contents of a tab. The getSelectedIndex() just returns that the first tab is currently selected (it would return -1 for no tabs selected)




回答2:


You're confusing the two sets of methods in JTabbedPane: the tab component methods and the component methods.

getTabComponentAt(0) is returning null because you haven't set the tab component. You've set the component that is displayed at index 0, but the tab component is the component that renders the tab--not the component that displays in the pane.

(Notice the example in the Javadocs:

// In this case the look and feel renders the title for the tab.
tabbedPane.addTab("Tab", myComponent);
// In this case the custom component is responsible for rendering the
// title of the tab.
tabbedPane.addTab(null, myComponent);
tabbedPane.setTabComponentAt(0, new JLabel("Tab"));

The latter is typically used when you want a more complex user interaction that requires custom components on the tab. For example, you could provide a custom component that animates or one that has widgets for closing the tab.

Normally, you won't need to mess with tab components.)

Anyway, try getComponentAt(0) instead.



来源:https://stackoverflow.com/questions/988734/jtabbedpane-gettabcomponentatint-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!