Question

I'm using the following code to let my component register/unregister event listeners when it's added/removed respectively.

addAncestorListener(new AncestorListener() {
        @Override public void ancestorRemoved(AncestorEvent event) {
            log.info("========= Remove listeners by " + ContentViewingComponent.this);
            ...
        }
        @Override public void ancestorMoved(AncestorEvent event) {}
        @Override public void ancestorAdded(AncestorEvent event) {
            log.info("========= Add listeners by " + ContentViewingComponent.this);
            ...
        }
    });

My intent was that both events (add and remove) would basically fire once in most situations, i.e. when the component is created & added and when it's removed & forgotten.

However, it turns out that they are also fired when the tab (of JTabbedPane) which this component is in gets selected/hidden. Is there a way to circumvent/detect that?

Maybe a version of JTabbedPane that uses showing/hiding instead of adding/removing? Update: More investigation shows that the component is not actually removed, but the tab hidden, and ancestorRemoved() fires for that too. I can detect whether the component still has a root* and ignore the event if it has, but the problem is that it won't be fired again when the component is actually removed (while invisible).

*Well, that remains to be seen. It appears ancestorRemoved() fires before the actual removal, so I cannnot walk up the getParent() chain to find out whether the component has a root. Update: Fixed by checking it one step later using SwingUtilities.invokeLater().


(For those familiar with Flash/AS3, I'm looking for a Swing equivalent of the ADDED_TO_STAGE/REMOVED_FROM_STAGE events.)

Was it helpful?

Solution 2

My intent was that both events (add and remove) would basically fire once in most situations, i.e. when the component is created & added and when it's removed & forgotten

there are AncestorListener, ComponentListener and HierarchyListener and could be asynchronous, same ways you can to getComponent, from those events or ancestor by using SwingUtilities

for example

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

public class MyTabbedPane {

    private JTabbedPane tabbedPane = new JTabbedPane();
    private JFrame f = new JFrame();
    private JLabel label1 = new JLabel("Tab1");
    private JLabel label2 = new JLabel("Tab2");
    private JLabel label3 = new JLabel("Tab3");
    private JLabel label4 = new JLabel("Tab4");

    public MyTabbedPane() {
        tabbedPane.addTab("Tab1", label1);
        tabbedPane.addTab("Tab2", label2);
        tabbedPane.addTab("Tab3", label3);
        tabbedPane.addTab("Tab4", label4);
        tabbedPane.setTabPlacement(JTabbedPane.TOP);
        tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

        label1.addAncestorListener(new EventHandler());
        label2.addAncestorListener(new EventHandler());
        label3.addAncestorListener(new EventHandler());
        label4.addAncestorListener(new EventHandler());

        label1.addHierarchyListener(new EventHandler());
        label2.addHierarchyListener(new EventHandler());
        label3.addHierarchyListener(new EventHandler());
        label4.addAncestorListener(new EventHandler());

        label1.addComponentListener(new EventHandler());
        label2.addComponentListener(new EventHandler());
        label3.addComponentListener(new EventHandler());
        label4.addComponentListener(new EventHandler());

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(tabbedPane, BorderLayout.CENTER);
        f.setPreferredSize(new Dimension(600, 400));
        f.pack();
        f.setVisible(true);
    }

    class EventHandler implements AncestorListener, ComponentListener, HierarchyListener {

        @Override
        public void ancestorAdded(AncestorEvent event) {
            System.out.println("CardlayoutTest.EventHandler.ancestorAdded()");
        }

        @Override
        public void ancestorMoved(AncestorEvent event) {
            System.out.println("CardlayoutTest.EventHandler.ancestorMoved()");
        }

        @Override
        public void ancestorRemoved(AncestorEvent event) {
            System.out.println("CardlayoutTest.EventHandler.ancestorRemoved()");
        }

        @Override
        public void hierarchyChanged(HierarchyEvent e) {
            System.out.println("Components Change: " + e.getChanged());
            if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
                if (e.getComponent().isDisplayable()) {
                    System.out.println("Components DISPLAYABILITY_CHANGED : " + e.getChanged());
                } else {
                    System.out.println("Components DISPLAYABILITY_CHANGED : " + e.getChanged());
                }
            }
            if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
                if (e.getComponent().isDisplayable()) {
                    System.out.println("Components SHOWING_CHANGED : " + e.getChanged());
                } else {
                    System.out.println("Components SHOWING_CHANGED : " + e.getChanged());
                }
            }
        }

        @Override
        public void componentHidden(ComponentEvent e) {
            System.out.println(e.getComponent().getClass().getName() + " --- Hidden");
        }

        @Override
        public void componentMoved(ComponentEvent e) {
            System.out.println(e.getComponent().getClass().getName() + " --- Moved");
        }

        @Override
        public void componentResized(ComponentEvent e) {
            System.out.println(e.getComponent().getClass().getName() + " --- Resized ");
        }

        @Override
        public void componentShown(ComponentEvent e) {
            System.out.println(e.getComponent().getClass().getName() + " --- Shown");
        }
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                MyTabbedPane frame = new MyTabbedPane();

            }
        });
    }
}

OTHER TIPS

Fixed by using a HierarchyListener.

public static void addDisplayableListeners(final Component comp, final Runnable onDisplayable, final Runnable onNotDisplayable) {
    comp.addHierarchyListener(new HierarchyListener() {
        @Override public void hierarchyChanged(HierarchyEvent e) {
            System.out.println("HIERARCHY CHANGE ===== " + comp);
            final boolean dc = (e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0;
            if (dc) {
                System.out.println("DISPLAYABILITY_CHANGED");
                if (comp.isDisplayable()) {
                    onDisplayable.run();
                } else {
                    onNotDisplayable.run();
                }
            }
        }
    });
}

Old version:

    addHierarchyListener(new HierarchyListener() {

        private boolean hadRoot = false;

        @Override public void hierarchyChanged(HierarchyEvent e) {

            System.out.println("HIERARCHY CHANGE ===== " + ContentViewingComponent.this);

            final boolean hasRoot = Swing.hasRoot(ContentViewingComponent.this);
            System.out.println("Has root: " + hasRoot);

            if (hasRoot != hadRoot) {

                System.out.println("...which is not what was.");
                hadRoot = hasRoot;

                if (hasRoot) {
                    log.info("========= Add listeners by " + ContentViewingComponent.this);
                    ...
                } else {
                    log.info("========= Remove listeners by " + ContentViewingComponent.this);
                    ...
                }
            }

        }
    });

Note: I'll look if I can replace my own helpers (hadRoot and hasRoot()) here with the official methods mentioned in @mKorbel's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top