【问题标题】:How to control a panel nested in JtabbedPane ?如何控制嵌套在 JtabbedPane 中的面板?
【发布时间】:2014-04-15 18:10:21
【问题描述】:

我有一个MainJtabbedPane,其中包含多个JtabbedPanes,每个JtabbedPanes 包含多个面板。

我需要能够从MainJtabbedPane 访问面板。

JTabbedPane[] components = (JTabbedPane[]) Main_Tabbed_Panel.getComponents();

for(int i=0; i<components.length;i++)
{
for(int j=0;j<components[i].getTabCount();j++)
{
.....
}
}

给出一个错误 java.awt.component cannot be cast to javax.swing.JtabbedPane

【问题讨论】:

  • 您能否向我们展示完整的堆栈跟踪以及堆栈跟踪的相关代码?
  • Main_Tabbed_Panel.getComponents() 是 Component[],而不是 JTabbedPane[],所以这是转换错误。

标签: java swing parent-child jtabbedpane


【解决方案1】:
JTabbedPane[] components = (JTabbedPane[]) Main_Tabbed_Panel.getComponents();

getComponents() 方法返回一个组件数组。即使您知道所有组件都将是 JTabbedPane 的实例,您也不能只将它们转换为 JTabbedPane。你需要像这样构建你的代码:

for(Component component: main_Tabbed_Panel.getComponents())
{
    if (component instanceof JTabbedPane)
    {
        JTabbedPane tabbePane = (JTabbedPane)component;

        // do something with the tabbed pane
    }
}

此外,请遵循 Java 命名约定。变量名不应以大写字符开头。 (即“Main_Tabbed_Pane 不遵循约定)。

【讨论】:

  • Variable name should NOT start with an upper case character - 除非它是常数 :) +1 指出惯例和简化算法
  • 谢谢你这很好,感谢大会问题
【解决方案2】:

(JTabbedPane[]) 转换为(Component[])。如果您将鼠标悬停在 getComponents() 方法上,您会看到它返回 Component[]

如果您想将 Component[] 转换为 JTabbedPane[],您需要手动进行,并确保在此过程中检查错误(在将其添加到 JTabbedPane 之前确保它是一个 JTabbedPane[] )

JTabbedPane[] panes = convertComponents(getComponents());

private JTabbedPane[] convertComponents(Component[] comps) {
    JTabbedPane[] panes = comps.length > 0? new JTabbedPane[comps.length] : null;
    if(panes != null)
        for(int i = 0; i < panes.length; i++) {
            if(comps[i] instanceof JTabbedPane)
            panes[i] = (JTabbedPane) comps[i];
        }
    return panes;
}

虽然这不是最有效的,因为对于 getComponents() 中不是 JTabbedPane 的每个项目,您的 JTabbedPane 数组中都会有一个空白点,然后您必须清理它。

JTabbedPane[] panes = comps.length &gt; 0? new JTabbedPane[comps.length] : null;

这首先检查通过参数传递的 Component[] 是否有 1 个或多个空格。如果没有,请不要使用实例进行初始化。

if(panes != null)

由于panes 有可能初始化为null,因此我们在尝试使用它之前会进行多次检查

for(int i = 0; i &lt; panes.length-1; i++) {

由于Component[] compsJTabbedPane[] panes 的大小相同,所以无论您使用哪个长度,只要我们知道循环多少次即可。

if(comps[i] instanceof JTabbedPane)

这就是我所说的“如果组件不是JTabbedPane,那么您的数组中将有一个空空间”的意思。这将在将其放入我们的窗格数组之前检查它是否为JTabbedPane。如果不是,则完全忽略,panes 中的空格保留为 null

循环完成后,会返回我们刚刚制作的数组。

【讨论】:

  • 如何获得第二个循环的 Tab Count 或 length?这是我的担心
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 2014-04-12
  • 2021-03-01
相关资源
最近更新 更多