How to set a font to LabelField text in Blackberry?

前端 未结 2 875
情话喂你
情话喂你 2021-02-03 15:53

I don\'t know how to apply font style to a text in a LabelField in Blackberry.

2条回答
  •  长发绾君心
    2021-02-03 16:24

    You can just use LabelField.setFont. If you don't do this explicitly on the label field, the field will use whatever font is used by its manager (and so on upward up the hierarchy).

    There are a couple of ways to get a font. One is to derive one from an existing font (in this case I'm getting a bold version of the default font):

    LabelField labelField = new LabelField("Hello World");
    Font myFont = Font.getDefault().derive(Font.BOLD, 9, Ui.UNITS_pt);
    labelField.setFont(myFont);
    

    The other is to get a specific font family and derive a font from that (here getting a 12 pt italic font):

    LabelField labelField = new LabelField("Hello World");
    FontFamily fontFamily = FontFamily.forName("BBCasual");
    Font myFont = fontFamily.derive(Font.ITALIC, 12, Ui.UNITS_pt);
    labelField.setFont(myFont);
    

    A couple of things to note: I used UNITS_pt (points) instead of UNITS_px (pixels). This is a good idea generally since BlackBerry devices vary quite a bit in screen size and resolution (DPI) and using points will give you a more consistent look across devices, instead of having your text look tiny on a Bold or 8900 (or huge on a Curve or Pearl).

    Also in the second example, forName can throw a ClassCastException which you have to catch (it's a checked exception) but is never actually thrown according to the Javadocs, if you specify an unknown name, it'll fall back to another font family.

提交回复
热议问题