001package jmri.jmrit.display;
002
003import javax.swing.BoxLayout;
004import javax.swing.Icon;
005import javax.swing.JButton;
006import javax.swing.JLabel;
007import javax.swing.JPanel;
008import jmri.jmrit.catalog.CatalogPane;
009import jmri.jmrit.catalog.NamedIcon;
010
011/**
012 * Provides a simple editor for selecting N NamedIcons, perhaps for use in
013 * creating a panel icon.
014 * <p>
015 * See {@link SensorIcon} for an item that might want to have that type of
016 * information, and {@link jmri.jmrit.display.panelEditor.PanelEditor} for an
017 * example of how to use this.
018 *
019 * @author Bob Jacobsen Copyright (c) 2003
020 * @see jmri.jmrit.display.SensorIcon
021 * @see jmri.jmrit.display.panelEditor.PanelEditor
022 * @see jmri.jmrit.catalog
023 */
024public class MultiIconEditor extends JPanel {
025
026    JButton[] buttonList;
027    NamedIcon[] iconList;
028
029    public CatalogPane catalog = new CatalogPane();
030
031    public MultiIconEditor(int nIcons) {
032        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
033
034        buttonList = new JButton[nIcons];
035        iconList = new NamedIcon[nIcons];
036
037    }
038
039    public void setIcon(int iconNum, String label, String name) {
040        iconList[iconNum] = new NamedIcon(name, name);
041        // make a button to change that icon
042        JButton j = new IconButton(iconNum, iconList[iconNum]);
043        j.setToolTipText(iconList[iconNum].getName());
044        buttonList[iconNum] = j;
045
046        // and add it to this panel
047        JPanel p = new JPanel();
048        p.add(new JLabel(label));
049        p.add(j);
050        this.add(p);
051    }
052
053    /**
054     * Returns a new NamedIcon object for your own use.
055     *
056     * @param iconNum 0 to n-1
057     * @return Unique object
058     */
059    public NamedIcon getIcon(int iconNum) {
060        return new NamedIcon(iconList[iconNum]);
061    }
062
063    public void complete() {
064        // add the catalog, so icons can be selected
065        this.add(catalog);
066    }
067
068    private class IconButton extends JButton {
069
070        IconButton(int index, Icon init) {  // init icon passed to avoid ref before ctor complete
071            super(init);
072            savedIndex = index;
073            addActionListener(a -> pickIcon());
074        }
075
076        int savedIndex;
077
078        void pickIcon() {
079            NamedIcon newIcon = catalog.getSelectedIcon();
080            iconList[savedIndex] = newIcon;
081            buttonList[savedIndex].setIcon(newIcon);
082        }
083    }
084
085    /**
086     * Clean up when its time to make it all go away
087     */
088    public void dispose() {
089        // clean up GUI aspects
090        this.removeAll();
091        iconList = null;
092        buttonList = null;
093        catalog = null;
094    }
095}