如何在resize时更改JLabel字体大小以填充JPanel可用空间?

这里有一个类似的问题: 如何更改JLabel字体的大小以获取最大大小

但它不适用于倒退。

因此,如果你让JPanel变大,字体就会增长,但是如果你使它更小, JLabel大小和字体仍然像以前一样

检查此图片

如何在resize时根据JPanel大小使Jlabel字体增长?

通过使用FontMetrics和TextLayout,您可以获得此输出(请阅读代码中的注释)

SwingUtilities也可以正确地做到这一点

我建议在两个方向上添加几个像素

将ComponentListener添加到容器,并在componentResized事件上重新计算FontMetrics

在此处输入图像描述

 import java.awt.*; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import javax.swing.*; public class ShowFontMetrics extends JFrame { private static final long serialVersionUID = 1L; private JLabel lTime; public ShowFontMetrics() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel pane = new JPanel(); pane.setLayout(new FlowLayout()); lTime = new JLabel("88:88"); lTime.setFont(new Font("Helvetica", Font.PLAIN, 88)); FontMetrics fm = lTime.getFontMetrics(lTime.getFont()); TextLayout layout = new TextLayout(lTime.getText(), lTime.getFont(), fm.getFontRenderContext()); Rectangle2D bounds = layout.getBounds(); Dimension d = lTime.getPreferredSize(); d.height = (int) (bounds.getHeight() + 100);// add huge amount of pixels just for for fun d.width = (int) (bounds.getWidth() + 150);// add huge amount of pixels just for for fun lTime.setPreferredSize(d); lTime.setVerticalAlignment(SwingConstants.CENTER); lTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); pane.add(lTime); setContentPane(pane); } public static void main(String[] arguments) { ShowFontMetrics frame = new ShowFontMetrics(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } } 

像这样? http://java-sl.com/tip_adapt_label_font_size.html

更新:

请求的代码

 import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; public class ResizeLabelFont extends JLabel { public static final int MIN_FONT_SIZE=3; public static final int MAX_FONT_SIZE=240; Graphics g; public ResizeLabelFont(String text) { super(text); init(); } protected void init() { addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { adaptLabelFont(ResizeLabelFont.this); } }); } protected void adaptLabelFont(JLabel l) { if (g==null) { return; } Rectangle r=l.getBounds(); int fontSize=MIN_FONT_SIZE; Font f=l.getFont(); Rectangle r1=new Rectangle(); Rectangle r2=new Rectangle(); while (fontSize 

好的,这是答案。

让我们从这里获取代码: 如何更改JLabel的字体大小以获取最大大小 ,从coobird回答

 int componentWidth = label.getWidth(); 

我们需要从JFrame组件获取宽度,而不是从JLabel获取宽度,因为代码不会让机会改变JLabel的大小。

这将解决它:

 int componentWidth = this.getWidth()-20; // '20' - according width of Jlabel to JFrame