Search code examples
javafontsformattingswtstyledtext

Java StyledText, appending text with different font?


I am new to Java and would like to know how to set the font and font color to be used for the next text to be added to a SWT StyledText box.

So for example I have an application that defines "command" and "data" text and each is to be displayed in a different font/color. So let's say I've just added some "command" text. Now how do I set things up so that the next text which will be "data" text is displayed in a different font and color?

I've done a lot of googling, but nothing seems to be helping me.

P.S.: This can't be the most efficient way to do it:

int a = st.getCharCount();

Font font = new Font(shlProtruleModifier.getDisplay(), "Courier", 10, SWT.NORMAL);

StyleRange[] sr = new StyleRange[1];

sr[0] = new StyleRange();

st.append("\r\nWhat the heck?");

sr[0].start = a;
sr[0].length = st.getCharCount() - a;
sr[0].font = font;
sr[0].foreground = SWTResourceManager.getColor(SWT.COLOR_BLACK);

st.replaceStyleRanges(sr[0].start, sr[0].length, sr);

Solution

  • So all I've been able to come up with the following technique that does work,

    int a = st.getCharCount();
    
    Font font = new Font(shlProtruleModifier.getDisplay(), "Courier", 10, SWT.NORMAL);
    
    StyleRange[] sr = new StyleRange[1];
    
    sr[0] = new StyleRange();
    
    st.append("\r\nWhat the heck?");
    
    sr[0].start = a;
    sr[0].length = st.getCharCount() - a;
    sr[0].font = font;
    sr[0].foreground = SWTResourceManager.getColor(SWT.COLOR_BLACK);
    
    st.replaceStyleRanges(sr[0].start, sr[0].length, sr);