在JLabel中制作文本会动态调整大小

时间:2011-01-21 05:03:24

标签: java swing jlabel layout-manager

我有一个Java Swing JLabel数组。我的程序的用户可以向JFrame添加一个新的JLabel,我想根据框架中的JLabel数量使JLabel中文本的大小发生变化。如果JLabel太多,则文本仍然适合,并且不会与其他JLabel重叠。

1 个答案:

答案 0 :(得分:2)

看起来不是很漂亮,但如果这就是你想要的,这里有一段快速编译和运行的代码。随意提取项目所需的任何代码。玩得开心, - 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);
}}