从子类更新父类ui

pieyvz9o  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(224)

我有一个swing应用程序。这里是我试图做的简化视图。

这个 mainFrame 是保存应用程序中所有组件的父框架。它有一个孩子叫 jPanel .
这个 jPanel 有个孩子叫 button . 什么时候 button 我想从中删除“jpanel” mainFrame 并添加一个不同的面板。
注:臀部可能是婴儿的直接子女 jPanel 或者一个孩子 jPanel 的子项(即:jpanel>>某些其他面板>>按钮)
基本上,我需要一个广播接收器类型的功能,安卓android广播接收器示例

w41d8nur

w41d8nur1#

“注意:button可以是jpanel的直接子对象,也可以是jpanel的子对象”
不会发生的。一个组件只能有一个父容器。
“jpanel有一个孩子叫button。单击按钮时,我想从大型机中删除“jpanel”并添加一个不同的面板。“
一个比添加和删除面板更干净的方法是使用 CardLayout 面板“分层”并可通过 CardLayout 的方法,如 show() , previous() , next() . 了解如何使用cardlayout。这里有一个简单的例子,如果您碰巧正在使用gui builder工具,请参阅如何将cardlayout与netbeans gui builder一起使用。即使您不使用gui builder,我仍然会查看链接以了解其工作方式。

dly7yett

dly7yett2#

最后我做了以下几件事。不是最好的,但很有效。

//get the container
Container tempContainer = MetricTablesX.this.getTopLevelAncestor();
if (tempContainer == null || tempContainer.getComponentCount() == 0) {
    return;
}

//get the root pane
Component rootPane = tempContainer.getComponent(0);
if (rootPane == null || !(rootPane instanceof JRootPane)) {
    return;
}
JRootPane pane = (JRootPane) rootPane;
if (pane == null || pane.getComponentCount() == 0) {
    return;
}

//get the layer Pane
Component jLayerPane = pane.getComponent(1);
if (jLayerPane == null || !(jLayerPane instanceof JLayeredPane)) {
    return;
}
JLayeredPane layerPane = (JLayeredPane) jLayerPane;
if (layerPane == null || layerPane.getComponentCount() == 0) {
    return;
}

//get the junk panel
Component jPanel = layerPane.getComponent(0);
if (jPanel == null || !(jPanel instanceof JPanel)) {
    return;
}
JPanel junkPanel = (JPanel) jPanel;
if (junkPanel == null || junkPanel.getComponentCount() == 0) {
    return;
}

//get the main panel
Component mPanel = junkPanel.getComponent(0);
if (mPanel == null || !(mPanel instanceof JPanel)) {
    return;
}
JPanel mainPanel = (JPanel) mPanel;
if (mainPanel == null || mainPanel.getComponentCount() == 0) {
    return;
}

//get the dashHolder
for (int i = 0; i < mainPanel.getComponentCount(); i++) {
    Component dPanel = mainPanel.getComponent(i);
    if (dPanel == null || !(dPanel instanceof JPanel)) {
        return;
    }
    JPanel dashHolderPanel = (JPanel) dPanel;
    if (dashHolderPanel.getName().equalsIgnoreCase("dashHolderPanel")) {
        RetailRegionDashboard retailRegionDash = new RetailRegionDashboard(cell.mtr);
        dashHolderPanel.removeAll();
        dashHolderPanel.add(retailRegionDash);
        dashHolderPanel.revalidate();
        dashHolderPanel.repaint();
    }
}

相关问题