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