package de.duehl.swing.ui.tabs.unused;

import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Hashtable;

import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * Diese Klasse merkt sich welches Objekt in welchem Reiter zuletzt den Fokus hatte und stellt
 * diesen wieder her.
 *
 * Siehe:
 *
 * https://stackoverflow.com/questions/6747795/jtabbedpane-focus-last-focused-component-after-tab-change
 *
 * @version 1.01     2017-11-22
 * @author Christian Dühl
 */


public class FocussingTabbedPane extends JTabbedPane
        implements ChangeListener, PropertyChangeListener {

    private static final long serialVersionUID = 1L;

    private final Hashtable<String, Component> tabFocus;

    public FocussingTabbedPane() {
        tabFocus = new Hashtable<>();
        init();
    }

    public FocussingTabbedPane(int tabPlacement, int tabLayoutPolicy) {
        super(tabPlacement, tabLayoutPolicy);
        tabFocus = new Hashtable<>();
        init();
    }

    private void init() {
        addChangeListener(this);
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(this);
    }

    @Override
    public void propertyChange(PropertyChangeEvent e) {
        if ("permanentFocusOwner".equals(e.getPropertyName())) {
            Object value = e.getNewValue();
            if (value != null) {
                int selectedIndex = getSelectedIndex();
                String title = getTitleAt(selectedIndex);
                tabFocus.put(title, (Component) value);
            }
        }

    }

    @Override
    public void stateChanged(ChangeEvent e) {
        Component value = tabFocus.get(getTitleAt(getSelectedIndex()));
        if (value != null) {
            value.requestFocusInWindow();
        }
    }

}