I have an array of Java Swing JLabels. The user of my program can add a new JLabel to the JFrame, and I want to make the size of the text in the JLabel change based on the number of JLabels in the frame. If there are too many JLabels, the text will still fit and will not overlap other JLabels.
You can set a fixed the size by setting the minimum, preferred and maximum size: setMinimumSize(width, height); setPreferredSize(width, height); setMaximumSize(width, height);
getSize() * widthRatio); int componentHeight = label. getHeight(); // Pick a new font size so it will not be larger than the height of label. int fontSizeToUse = Math. min(newFontSize, componentHeight); // Set the label's font size to the newly determined size.
Yes you can do it :D.
Doesnt look pretty, but if that is what you want, here's a quick piece of code to compile and run. Feel free to extract whatever code you need for your project. Have fun, - M.S.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LabelSize extends JPanel {
private Font font;
private JPanel panel;
private JLabel label = new JLabel ("Font Size Adapter Label", JLabel.CENTER);
private JTextField tf = new JTextField ("Type in text for new label here and hit [Enter]");
public LabelSize() {
super (new BorderLayout());
panel = labelPanel();
add (panel, "North");
add (tf, "South");
tf.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
label.setText (tf.getText());
label.setFont (font);
int labelW = (int) Math.ceil (label.getPreferredSize().getWidth());
int maxWidth = (int) Math.floor (panel.getSize().getWidth());
if (labelW <= maxWidth)
return;
for (int k = 1 ; labelW > maxWidth ; k++) {
Font labelFont = font.deriveFont (font.getSize() - k*1.0f);
label.setFont (labelFont);
labelW = (int) Math.ceil (label.getPreferredSize().getWidth());
}}});
}
private JPanel labelPanel() {
JPanel lp = new JPanel(new BorderLayout());
lp.setPreferredSize (new Dimension (270,30));
lp.add (label, "North");
font = label.getFont();
return lp;
}
public static void main (String[] args) {
JFrame lsFrame = new JFrame ("Lfit");
lsFrame.add (new LabelSize());
lsFrame.pack();
lsFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
lsFrame.setVisible(true);
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With