javafontsswtstyledtextmonospace

Java SWT - StyledText how to show text using monospaced font


Is there any way to force StyledText widget to show text using monospaced font? It's not a problem of used font - I have tried 'Monospace', 'Courier', 'System', 'Fixedsys' and other monospaced fonts... Normal Text widget shows text with monospaced font defaultly ('Fixedsys' font tested).

Thanks in advance for help!


Solution

  • You can get a monospaced font with the methods shown in the answers to this question:

    SWT - OS agnostic way to get monospaced font

    Then simply call StyledText#setFont(Font):

    public static void main(String[] args)
    {
        Display display = new Display();
        Shell shell = new Shell();
        shell.setText("StackOverflow");
        shell.setLayout(new FillLayout());
    
        StyledText text = new StyledText(shell, SWT.BORDER | SWT.MULTI);
        text.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
        text.setText("|i|m|\n|m|i|");
    
        shell.pack();
        shell.setSize(200, 100);
        shell.open();
    
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
        display.dispose();
    }
    

    Looks like this:

    enter image description here