Search code examples
javaoutputjtextarea

Trying to display a JSON (asText) output in JTextAreaInterface


I have a program that displays information as a JSON (astext). In the netbeans consol the output looks fine like this one:

------------------------
| res1                 |
========================
| "Houben,-Henriette"  |
| "Maiterth,-Ralf"     |
| "Müller,-Heiko"      |
| "Herr,-Hansjörg"     |
| "Schneider,-Georg"   |
------------------------

But the result in the JTextAreaInterface looks like this:

----------------
| res1            |
==================
| "Houben,-Henriette"  |
| "Maiterth,-Ralf"   |
| "Müller,-Heiko"      |
| "Herr,-Hansjörg" |
| "Schneider,-Georg  |

------------------------

And the problem is worse when I have a two or three columns result. Is there a way to fix it? This is my JTextAreaInterface :

public class JTextAreaInterface extends OutputStream {
    public static JTextArea textArea = new JTextArea(25, 80);
    private final JTextArea destination;

    public JTextAreaInterface(JTextArea destination) {
        if (destination == null)
            throw new IllegalArgumentException("Destination is null");
        this.destination = destination;
    }

    @Override
    public void write(byte[] buffer, int offset, int length) throws IOException {
        final String text = new String(buffer, offset, length);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                destination.append(text);
            }
        });
    }

    @Override
    public void write(int b) throws IOException {
        write(new byte[] { (byte) b }, 0, 1);
    }

    public static void main(String[] args) throws Exception {
        textArea.setEditable(false);
        JFrame frame = new JFrame("Processing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
        JTextAreaInterface out = new JTextAreaInterface(textArea);
        System.setOut(new PrintStream(out));
        MyProgram test = new MyProgram();
        test.Processing();

            System.setOut(new PrintStream(out, true));
            System.setErr(new PrintStream(out, true));
    }
}

Solution

  • You need to use JTextArea.setFont() to set a monospaced font, such as Courier, for the text area.