JTabbedPane.getTabComponentAt(int)返回null

Geo*_*Geo 5 java swing jtabbedpane

我有以下代码:

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);
Run Code Online (Sandbox Code Playgroud)

事情是 :

container.getTabComponentAt(0)
Run Code Online (Sandbox Code Playgroud)

回报null.另一个奇怪的事情是:

container.getSelectedIndex()
Run Code Online (Sandbox Code Playgroud)

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

aka*_*okd 18

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


Mic*_*ers 7

您将以下两组方法混淆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"));
Run Code Online (Sandbox Code Playgroud)

当您需要更复杂的用户交互(需要选项卡上的自定义组件)时,通常会使用后者.例如,您可以提供动画的自定义组件或具有用于关闭选项卡的小组件的自定义组件.

通常,您不需要乱用标签组件.)

不管怎么说,试试吧getComponentAt(0).