2009-06-12 63 views
3

我有以下代码:JTabbedPane.getTabComponentAt(INT)返回null

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); 

的事情是:

container.getTabComponentAt(0) 

回报null。另一个奇怪的是:

container.getSelectedIndex() 

返回0。我认为应该发生的合乎逻辑的事情是对已创建的窗口进行引用。为什么我收到null?我究竟做错了什么?

回答

14

getTabComponentAt()返回您可能添加的自定义组件作为选项卡标题。您可能正在寻找getComponentAt()方法来返回标签的内容。 getSelectedIndex()只是返回第一个选项卡当前选中(它将返回-1没有选项卡选择)

6

你混淆了JTabbedPane中的两组方法:选项卡组件方法和组件方法。

getTabComponentAt(0)正在返回null,因为您尚未设置选项卡组件。您已设置在索引0处显示的组件,但选项卡组件是呈现选项卡的组件 - 而不是显示在窗格中的组件。

(注意在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")); 

当你想要求的标签上的定制组件的更复杂的用户交互,后者通常用于例如,可以提供自定义组件动画或一个有小部件关闭标签。

通常情况下,你不会需要与标签成分混乱。)

无论如何,请改为尝试getComponentAt(0)