【问题标题】:JTabbedPane.getTabComponentAt(int) returning nullJTabbedPane.getTabComponentAt(int) 返回 null
【发布时间】:2009-06-12 19:56:17
【问题描述】:

我有以下代码:

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?我做错了什么?

【问题讨论】:

    标签: java swing jtabbedpane


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      (注意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)吧。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        • 2014-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-18
        相关资源
        最近更新 更多