net.alantea.swing.vml.widgets.LabelHandler Maven / Gradle / Ivy
package net.alantea.swing.vml.widgets;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import net.alantea.liteprops.Property;
import net.alantea.swing.vml.BaseSwingHandler;
import net.alantea.viewml.annotations.VAttribute;
import net.alantea.viewml.annotations.VElement;
@VElement("label")
public class LabelHandler extends BaseSwingHandler
{
private ImageIcon icon;
private Property label = new Property<>();
public LabelHandler()
{
super(new JLabel());
init();
}
protected LabelHandler(JLabel target)
{
super(target);
init();
}
private void init()
{
label.addListener((o, n) -> setText(n));
getComponent().addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
JLabel label = (JLabel)getComponent();
int compWidth = label.getWidth();
int compHeight = label.getHeight();
if ((compWidth <= 0) || (compHeight <= 0))
{
return;
}
// Recalculate the image
int iconWidth = (icon == null) ? 0 : icon.getIconWidth();
int iconHeight = (icon == null) ? 0 : icon.getIconHeight();
Image img = getScaledImage(icon, (iconWidth * compHeight) / iconHeight, compHeight);
((JLabel) getComponent()).setIcon(new ImageIcon(img));
// Recalculate the text font
int availableWidth = compWidth - ((icon == null) ? 0 : img.getWidth(null));
int availableHeight = compHeight;
Font labelFont = label.getFont();
String labelText = label.getText();
int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
// Find out how much the font can grow in width.
double widthRatio = (double)availableWidth / (double)stringWidth;
int newFontSize = (int)(labelFont.getSize() * widthRatio);
// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, availableHeight);
// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), labelFont.getStyle(), fontSizeToUse));
}
});
}
@VAttribute("text")
private void setText(String text)
{
((JLabel) getComponent()).setText(text);
}
@VAttribute("icon")
private void setIcon(String text)
{
icon = new ImageIcon(this.getClass().getResource((text)));
((JLabel) getComponent()).setIcon(icon);
}
private Image getScaledImage(ImageIcon srcImg, int w, int h)
{
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg.getImage(), 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy