Skip to content

Instantly share code, notes, and snippets.

@rodrigocananea
Created July 15, 2022 16:34
Show Gist options
  • Save rodrigocananea/3e10fb2eb9c8911bf15ffb56a2e30420 to your computer and use it in GitHub Desktop.
Save rodrigocananea/3e10fb2eb9c8911bf15ffb56a2e30420 to your computer and use it in GitHub Desktop.
JLabel responsiva, redimensionar conforme na largura/altura disponivel
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ELabelFontResize extends JLabel {
private Graphics g;
public ELabelFontResize() {
super();
super.addComponentListener(new LabelListener());
}
public ELabelFontResize(String text) {
super(text);
super.addComponentListener(new LabelListener());
}
private class LabelListener extends ComponentAdapter {
@Override
public void componentResized(ComponentEvent e) {
if (g == null) {
return;
}
Font labelFont = ELabelFontResize.this.getFont();
String labelText = ELabelFontResize.this.getText();
int stringWidth = ELabelFontResize.this.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = ELabelFontResize.this.getWidth();
double widthRatio = (double) componentWidth / (double) stringWidth;
int newFontSize = (int) (labelFont.getSize() * widthRatio);
int componentHeight = ELabelFontResize.this.getHeight();
int fontSizeToUse = Math.min(newFontSize, componentHeight);
setFont(labelFont.deriveFont(labelFont.getStyle(), fontSizeToUse));
repaint();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.g = g;
}
public static void main(String[] args) throws Exception {
EventQueue.invokeLater(() -> {
ELabelFontResize label = new ELabelFontResize("Redimensionar com base na altura e largura do espaço disponivel.");
JFrame frame = new JFrame("Resize label font");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
frame.setSize(650, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment