java gwt richtextarea change font-family

2019-06-22 12:04发布

问题:

The Object richtextarea of java gwt has as default the font-family 'times new roman' is it somehow possible to change the family to 'Arial'?

回答1:

You have several options. You can create a CSS class and set it on the body element of the document inside RichTextArea, or you can set the style attribute on it directly. If you want this change to be consistent throughout your app, I recommend creating a new class and adding an InitializeHandler to it.

public class MyRichTextArea extends RichTextArea {

    public MyRichTextArea() {

        addInitializeHandler(new InitializeHandler() {

            @Override
            public void onInitialize(InitializeEvent ie) {

                Document document = IFrameElement.as(getElement()).getContentDocument();
                BodyElement body = document.getBody();
                body.setAttribute("style", "font-family: Arial Unicode MS,Arial,sans-serif;");
            });
        }
    }
}


回答2:

It is better to use the provided functionality. If you want to change it at creation time, you will need the initializeHandler as mentioned in answer 1:

RichTextArea rta = new RichTextArea();
rta.addInitializeHandler(new InitializeHandler() {
    public void onInitialize(InitializeEvent event) {
            rta.getFormatter().setFontName("\"Trebuchet MS\",Trebuchet,Arial");
            rta.getFormatter().setFontSize(FontSize.SMALL);
            rta.getFormatter().setForeColor("#FF0000");
        }
    });

PS: you need to do this before you add any content to the textarea, or it will only be applied to new input.



回答3:

I've found more common solution:

addInitializeHandler(new InitializeHandler() {
        public void onInitialize(InitializeEvent ie) {
            Document document = IFrameElement.as(getElement()).getContentDocument(); 
            BodyElement body = document.getBody(); 
            HeadElement head = HeadElement.as(Element.as(body.getPreviousSibling())); 
            LinkElement styleLink = document.createLinkElement(); 
            styleLink.setType("text/css"); 
            styleLink.setRel("stylesheet"); 
            styleLink.setHref("richtextarea.css"); 
            head.appendChild(styleLink);
        } 
    }); 

After adding initialization handler, it's easy to change styles in richtextarea.css file



标签: java gwt fonts