Returns the mnemonic characters of an collection of components. - Java Swing

Java examples for Swing:Key Event

Description

Returns the mnemonic characters of an collection of components.

Demo Code


import java.awt.Component;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;

public class Main{
    private static final Map<Character, Integer> MNEMONIC_OF_CHAR = new HashMap<>();
    /**// w  w  w .j  ava  2  s  .  c o  m
     * Returns the mnemonic characters of an collection of components.
     *
     * @param  components {@code JButton}s and {@code JLabel} will be queried
     * @return            mnemonics
     */
    public static List<Character> getMnemonicCharsOf(
            Collection<? extends Component> components) {
        if (components == null) {
            throw new NullPointerException("components == null");
        }

        List<Character> mnemonics = new ArrayList<>(components.size());

        for (Component component : components) {
            setMnemonics(component);

            int mnemonic = 0;

            if (component instanceof JButton) {
                mnemonic = ((JButton) component).getMnemonic();
            } else if (component instanceof JLabel) {
                mnemonic = ((JLabel) component).getDisplayedMnemonic();
            }

            if (mnemonic > 0) {
                mnemonics.add((char) mnemonic);
            }
        }

        return mnemonics;
    }
    /**
     * Sets as mnemonic every character in all components of a container after
     * the first ampersand (&amp;):
     *
     * <ul>
     * <li>{@code JLabel#setDisplayedMnemonic(int)} (Do not forget to call
     *     {@code JLabel#setLabelFor(java.awt.Component)})
     * </li>
     * <li>{@code AbstractButton#setMnemonic(int)}</li>
     * <li>{@code JTabbedPane#setMnemonicAt(int, int)}</li>
     * </ul>
     *
     * <em>The valid range of mnemonic characters is [A-Za-z0-9]</em>.
     *
     * @param container container. All components of this container will
     *                  gathered recursively.
     *
     * @throws NullPointerException if <code>component</code> is null
     */
    public static void setMnemonics(Container container) {
        if (container == null) {
            throw new NullPointerException("container == null");
        }

        int count = container.getComponentCount();

        setMnemonics((Component) container);

        for (int i = 0; i < count; i++) {
            Component component = container.getComponent(i);

            setMnemonics(component);

            if (component instanceof Container) {
                setMnemonics((Container) component); // Recursive
            }
        }
    }
    /**
     * Sets as mnemonic every character in a (<em>one</em>) component after
     * the first ampersand (&amp;):
     *
     * <ul>
     * <li>{@code JLabel#setDisplayedMnemonic(int)} (Do not forget to call
     *     {@code JLabel#setLabelFor(java.awt.Component)})
     * </li>
     * <li>{@code AbstractButton#setMnemonic(int)}</li>
     * <li>{@code JTabbedPane#setMnemonicAt(int, int)}</li>
     * </ul>
     *
     * <em>The valid range of mnemonic characters is [A-Za-z0-9]</em>.
     *
     * @param component component
     *
     * @throws NullPointerException if <code>component</code> is null
     */
    public static void setMnemonics(Component component) {
        if (component == null) {
            throw new NullPointerException("component == null");
        }

        if (component instanceof JLabel) {
            JLabel label = (JLabel) component;
            String text = label.getText();
            if (text != null && !isHtmlText(text)) {
                MnemonicIndexString mnemonicIndexString = getMnemonic(text);
                if (hasMnemonic(mnemonicIndexString)) {
                    label.setText(mnemonicIndexString.string);
                    label.setDisplayedMnemonic(mnemonicIndexString.index);
                }
            }
        } else if (component instanceof AbstractButton) {
            AbstractButton button = (AbstractButton) component;
            String text = button.getText();
            if (text != null && !isHtmlText(text)) {
                MnemonicIndexString mnemonicIndexString = getMnemonic(text);
                if (hasMnemonic(mnemonicIndexString)) {
                    button.setText(mnemonicIndexString.string);
                    button.setMnemonic(mnemonicIndexString.index);
                }
            }
        } else if (component instanceof JTabbedPane) {
            TabbedPaneUtil.setMnemonics((JTabbedPane) component);
        }
    }
    /**
     * Returns a mnemonic of a masked string.
     *
     * The mask is the first ampersand (&amp;), the mnemonic is the character
     * behind the ampersand.
     *
     * <em>The valid range of mnemonic characters is [A-Za-z0-9]</em>.
     *
     * @param   string masked string or string without an ampersand
     * @return         {@code MnemonicIndexString#index} ist -1 if the
     *                 string does not contain an ampersand or the mnemonic
     *                 character is invalid. {@code MnemonicIndexString#string} is
     *                 the string without the mask, or the string itself if
     *                 {@code MnemonicIndexString#index} is -1.
     * @throws NullPointerException if <code>string</code> is null
     */
    static MnemonicIndexString getMnemonic(String string) {
        if (string == null) {
            throw new NullPointerException("string == null");
        }

        MnemonicIndexString noMnemonicIndexString = new MnemonicIndexString(
                -1, string);

        if (string.length() < 2) {
            return noMnemonicIndexString;
        }

        int strlen = string.length();
        int ampersandIndex = string.indexOf('&');

        if (ampersandIndex < 0) {
            return noMnemonicIndexString;
        }

        if ((strlen < 2) || (ampersandIndex < 0)
                || (ampersandIndex > strlen - 2)) {
            return noMnemonicIndexString;
        }

        char mnemonicChar = string
                .substring(ampersandIndex + 1, ampersandIndex + 2)
                .toUpperCase().charAt(0);
        boolean isInRange = MnemonicUtil.isInRange(mnemonicChar);

        assert isInRange : "Not in Range: " + mnemonicChar + " of "
                + string;

        if (isInRange) {
            int mnemonic = MnemonicUtil.getMnemonicOf(mnemonicChar);
            String titlePrefix = (ampersandIndex == 0) ? "" : string
                    .substring(0, ampersandIndex);
            String titlePostfix = (ampersandIndex == strlen - 1) ? ""
                    : string.substring(ampersandIndex + 1);

            return new MnemonicIndexString(mnemonic, titlePrefix
                    + titlePostfix);
        }

        return noMnemonicIndexString;
    }
    private static boolean isHtmlText(String string) {
        String lcString = string == null ? "" : string.toLowerCase().trim();
        return lcString.startsWith("<html");
    }
    private static boolean hasMnemonic(MnemonicIndexString p) {
        return MNEMONIC_OF_CHAR.containsValue(p.index);
    }
    public static boolean isInRange(char c) {
        return MNEMONIC_OF_CHAR.containsKey(c);
    }
    /**
     * Returns a mnemonic (index) of a specific character.
     *
     * @param  c character in range [A-Z,0-9]
     * @return   mnemonic
     * @throws   IllegalArgumentException if <code>c</code> is not in range
     */
    public static int getMnemonicOf(char c) {
        if (!isInRange(c)) {
            throw new IllegalArgumentException(
                    "Character is not in Range: " + c);
        }

        return MNEMONIC_OF_CHAR.get(c);
    }
}

Related Tutorials