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;
013
014/**
015 * A small user interface component that consists of an image label and
016 * a fixed text content to the right of the image.
017 * @since 5965
018 */
019public class ImageLabel extends JPanel {
020    private final JLabel imgLabel;
021    private final JLabel tf;
022    private final int charCount;
023
024    /**
025     * Constructs a new {@code ImageLabel}.
026     * @param img Image name (without extension) to find in {@code statusline} directory
027     * @param tooltip Tooltip text to display
028     * @param charCount Character count used to compute min/preferred size
029     * @param background The background color
030     */
031    public ImageLabel(String img, String tooltip, int charCount, Color background) {
032        setLayout(new GridBagLayout());
033        setBackground(background);
034        add(imgLabel = new JLabel(), GBC.std().anchor(GBC.WEST).insets(0, 1, 1, 0));
035        setIcon(img);
036        add(tf = new JLabel(), GBC.std().fill(GBC.BOTH).anchor(GBC.WEST).insets(2, 1, 1, 0));
037        setToolTipText(tooltip);
038        this.charCount = charCount;
039    }
040
041    /**
042     * Sets the text to display.
043     * @param t text to display
044     */
045    public void setText(String t) {
046        tf.setText(t);
047    }
048
049    /**
050     * Sets the image to display.
051     * @param img Image name (without extension) to find in {@code statusline} directory
052     */
053    public void setIcon(String img) {
054        imgLabel.setIcon(ImageProvider.get("statusline/" + img));
055    }
056
057    @Override
058    public Dimension getPreferredSize() {
059        return new Dimension(25 + charCount*tf.getFontMetrics(tf.getFont()).charWidth('0'), super.getPreferredSize().height);
060    }
061
062    @Override
063    public Dimension getMinimumSize() {
064        return new Dimension(25 + charCount*tf.getFontMetrics(tf.getFont()).charWidth('0'), super.getMinimumSize().height);
065    }
066}