Java Swing中的可变字体大小

时间:2016-10-02 20:26:45

标签: java

我正在寻找一种在Swing组件中创建字体的方法,例如JLabel和JTextField,它们可以按非整数大小进行缩放。使用JLabel进行测试显示字体大小仅显示为整数的磅值。 这是测试代码,显示不同字体大小的情况。

package test;

import java.awt.Container;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class TestFontSize
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater (new Runnable()
        {
            public void run()
            {
                showFrame();
            }
        });
    }

    private static void showFrame()
    {
        JFrame fontTestFrame = new JFrame();
        int iFrameLeft = 50;
        int iFrameTop = 20;         
        int iFrameWidth = 900;
        int iFrameHeight = 560;
        int iLabelWidth = iFrameWidth - iFrameLeft*2;
        fontTestFrame.setBounds(iFrameLeft, iFrameTop, iFrameWidth, iFrameHeight);
        fontTestFrame.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
        Container con = fontTestFrame.getContentPane();
        con.setLayout(null);

        Font lblBaseFont = new Font("Arial", Font.PLAIN, 16);
        int iLabelHeight = 22;
        float fInitialFontSize = 12;
        float fFontSizeIncrement = (float)0.09;
        int iInitialTopPosition = 10;
        int iNumLoops = (iFrameHeight-(25 + iInitialTopPosition*2))/(iLabelHeight+2);
        System.out.println("iNumLoops: " + iNumLoops);

        for (int i=0; i<iNumLoops; i++)
        {
            float fNewFontSize = (float)(fInitialFontSize + i*fFontSizeIncrement);
            int iVerticalPosition = iInitialTopPosition + i*(iLabelHeight+2);
            Font lblNewFont = lblBaseFont.deriveFont(fNewFontSize);
            JLabel lbl = new JLabel("The swift fox jumped over the lazy brown dog - Font sie: " + fNewFontSize);
            lbl.setFont(lblNewFont);
            lbl.setBounds(20, iVerticalPosition, iLabelWidth, iLabelHeight);
            con.add(lbl);
        }
        fontTestFrame.setVisible(true);
    }
}

如果你运行它,你会发现字体大小不会随着大小而缩放,而是会从一种尺寸跳到另一种尺寸。 我尝试使用导入的真实字体,在JLabel中使用affinetransform版本的derivedFont和html代码来指定字体大小。没有快乐。

有可能吗?

0 个答案:

没有答案