001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.dialogs.relation;
003
004import java.awt.Color;
005import java.awt.Component;
006
007import javax.swing.ImageIcon;
008import javax.swing.JLabel;
009import javax.swing.JTree;
010import javax.swing.tree.TreeCellRenderer;
011
012import org.openstreetmap.josm.data.osm.Relation;
013import org.openstreetmap.josm.gui.DefaultNameFormatter;
014import org.openstreetmap.josm.tools.ImageProvider;
015
016/**
017 * This is the cell renderer used in {@link RelationTree}.
018 *
019 *
020 */
021public class RelationTreeCellRenderer extends JLabel implements TreeCellRenderer {
022    public final static Color BGCOLOR_SELECTED = new Color(143,170,255);
023
024    /** the relation icon */
025    private ImageIcon icon;
026
027    /**
028     * constructor
029     */
030    public RelationTreeCellRenderer() {
031        icon = ImageProvider.get("data", "relation");
032        setOpaque(true);
033    }
034
035    /**
036     * renders the icon
037     */
038    protected void renderIcon() {
039        setIcon(icon);
040    }
041
042    /**
043     * renders the textual value. Uses the relations names as value
044     *
045     * @param relation the relation
046     */
047    protected void renderValue(Relation relation) {
048        setText(relation.getDisplayName(DefaultNameFormatter.getInstance()));
049    }
050
051    /**
052     * renders the background
053     *
054     * @param selected true, if the current node is selected
055     */
056    protected void renderBackground(boolean selected) {
057        Color bgColor = Color.WHITE;
058        if (selected) {
059            bgColor = BGCOLOR_SELECTED;
060        }
061        setBackground(bgColor);
062    }
063
064    @Override
065    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
066            boolean leaf, int row, boolean hasFocus) {
067
068        // Hackish fix for #7056 - if name template for duplicated relation contains tags from parent, template will fail because getReffers doesn't work on primitives not yet in dataset
069        if (!tree.isRootVisible() && tree.getModel().getRoot() == value)
070            return this;
071
072        renderIcon();
073        renderValue((Relation)value);
074        renderBackground(selected);
075        return this;
076    }
077
078}