octavian-nita
11/17/2014 - 2:09 PM

Simple Java / Swing console

Simple Java / Swing console

package net.codarium.util;

import static java.awt.Font.BOLD;
import static java.lang.Boolean.TRUE;
import static java.lang.System.getProperty;
import static javax.swing.JEditorPane.HONOR_DISPLAY_PROPERTIES;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import static javax.swing.SwingUtilities.invokeLater;
import static javax.swing.UIManager.getSystemLookAndFeelClassName;
import static javax.swing.UIManager.setLookAndFeel;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;

import javax.swing.BorderFactory;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

/**
 * @author Octavian Theodor NITA (mnothro@yahoo.com)
 * @version 1.0, Feb 17, 2014
 */
public class Console {

    public static final Console CON = new Console();

    private JFrame frame;

    private JEditorPane out;

    private void init() {
        out = new JEditorPane();
        out.putClientProperty(HONOR_DISPLAY_PROPERTIES, TRUE);
        out.setFont(new Font("monospaced", BOLD, 16));
        out.setPreferredSize(new Dimension(640, 480));
        out.setMargin(new Insets(5, 10, 5, 10));
        out.setEditable(false);

        JScrollPane scroll = new JScrollPane(out);
        scroll.setBorder(BorderFactory.createEmptyBorder());

        frame = new JFrame(getProperty("user.name", "nobody") + " on " + getProperty("os.name", ""));
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout());
        frame.add(scroll);
        frame.pack();
        frame.setLocationRelativeTo(null);
    }

    public static final String NL = System.getProperty("line.separator", "\n");

    public Console() {
        try {
            setLookAndFeel(getSystemLookAndFeelClassName());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        invokeLater(new Runnable() {

            @Override
            public void run() {
                init();
            }
        });
    }

    public Console p(final String fmt, final Object... args) {
        invokeLater(new Runnable() {

            @Override
            public void run() {
                if (!frame.isVisible()) {
                    frame.setVisible(true);
                }
                out.setText(out.getText() + String.format(fmt, args));
            }
        });
        return this;
    }

    public Console ln(String fmt, Object... args) {
        return p(fmt + "%n", args);
    }

    public Console ln() {
        return ln("");
    }

    public Console clear() {
        invokeLater(new Runnable() {

            @Override
            public void run() {
                if (!frame.isVisible()) {
                    frame.setVisible(true);
                }
                out.setText("");
            }
        });
        return this;
    }
}