001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004import java.awt.Color;
005import java.awt.Dimension;
006import java.awt.GridBagLayout;
007
008import javax.swing.JLabel;
009import javax.swing.JPanel;
010
011import org.openstreetmap.josm.tools.GBC;
012import org.openstreetmap.josm.tools.ImageProvider;
013import org.openstreetmap.josm.tools.ImageProvider.ImageSizes;
014
015/**
016 * A small user interface component that consists of an image label and
017 * a fixed text content to the right of the image.
018 * @since 5965
019 */
020public class ImageLabel extends JPanel {
021    private final JLabel imgLabel = new JLabel();
022    private final JLabel tf = new JLabel();
023    private int charCount;
024
025    /**
026     * Constructs a new {@code ImageLabel}.
027     * @param img Image name (without extension) to find in {@code statusline} directory
028     * @param tooltip Tooltip text to display
029     * @param charCount Character count used to compute min/preferred size
030     * @param background The background color
031     */
032    public ImageLabel(String img, String tooltip, int charCount, Color background) {
033        setLayout(new GridBagLayout());
034        setBackground(background);
035        add(imgLabel, GBC.std().anchor(GBC.WEST).insets(0, 1, 1, 0));
036        setIcon(img);
037        add(tf, GBC.std().fill(GBC.BOTH).anchor(GBC.WEST).insets(2, 1, 1, 0));
038        setToolTipText(tooltip);
039        setCharCount(charCount);
040    }
041
042    /**
043     * Sets the text to display.
044     * @param t text to display
045     */
046    public void setText(String t) {
047        tf.setText(t);
048    }
049
050    /**
051     * Sets the image to display.
052     * @param img Image name (without extension) to find in {@code statusline} directory
053     */
054    public void setIcon(String img) {
055        imgLabel.setIcon(ImageProvider.get("statusline/", img, ImageSizes.STATUSLINE));
056    }
057
058    @Override
059    public Dimension getPreferredSize() {
060        return new Dimension(25 + charCount*tf.getFontMetrics(tf.getFont()).charWidth('0'), super.getPreferredSize().height);
061    }
062
063    @Override
064    public Dimension getMinimumSize() {
065        return new Dimension(25 + charCount*tf.getFontMetrics(tf.getFont()).charWidth('0'), super.getMinimumSize().height);
066    }
067
068    /**
069     * Returns the preferred char count.
070     * @return the preferred char count
071     * @since 10191
072     */
073    public final int getCharCount() {
074        return charCount;
075    }
076
077    /**
078     * Sets the preferred char count.
079     * @param charCount the preferred char count
080     * @since 10191
081     */
082    public final void setCharCount(int charCount) {
083        this.charCount = charCount;
084    }
085}