【问题标题】:Font Enumeration Java字体枚举 Java
【发布时间】:2014-08-13 09:59:31
【问题描述】:

我对 Java 还很陌生,但学起来很快。目前,我正在创建的将文档写入 PDF 的程序使用多种字体。我想将这些声明为枚举(它们当前位于名为 Fonts 的类文件中,并声明为 public static final 可以正常工作)但我似乎无法弄清楚如何声明每个特定枚举等于什么字体即使在阅读之后关于枚举的几篇文档。我知道枚举是更明智的方法,所以如果可能的话,我更愿意实现它。

真的只是经过一些指导。

我的字体类文件如下。

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.CMYKColor;

public class Fonts {

public static final Font REG16 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 16));
public static final Font REG13 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 13));
public static final Font BOLD13 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 13, Font.BOLD, BaseColor.BLACK));
public static final Font BOLD11 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 11, Font.BOLD, BaseColor.BLACK));
public static final Font BOLD10 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 10, Font.BOLD, BaseColor.BLACK));
public static final Font GREY11 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 11, BaseColor.GRAY));
public static final Font GREYBOLD10 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 10, Font.BOLDITALIC, BaseColor.GRAY));
public static final Font REG10 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 10));
public static final Font REG11 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 11));
public static final Font GREYBOLD17 =  new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 17, Font.BOLDITALIC));
public static final Font WHITEBOLD38 =  new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 38, Font.BOLD, BaseColor.WHITE));
public static final Font WHITEBOLD20 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 20, Font.BOLD, BaseColor.WHITE));
public static final Font WHITEBOLD10 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 10, Font.BOLD, BaseColor.WHITE));                    // Declare fonts.
public static final Font BOLDITALIC11 =  new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 11, Font.BOLDITALIC, BaseColor.BLACK));
public static final Font ORANGEBOLD12 = new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 12, Font.BOLDITALIC, new CMYKColor(0, 0.2f, 1f, 0)));
}

【问题讨论】:

  • 硬编码路径...不是很便携。

标签: java enums


【解决方案1】:

您可以为每个实例创建一个带有Font 属性的enum

以下内容:

enum Fonts {

    REG16(new Font(FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", 16))),
    ...
    ;

    private Font f;

    Fonts(Font f) {
        this.f = f;
    }

    public Font getFont() {
        return this.f;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2011-04-07
    • 1970-01-01
    • 2013-01-04
    相关资源
    最近更新 更多