Java Console Standalone?

时间:2014-02-23 21:11:49

标签: java swing jar console jframe

我在java中创建了一个简单的JFrame。但是我也希望在打开真正的.jar文件的同时打开开发人员控制台。在第8行是我想在控制台窗口中输出的文本,该文本应该从JFrame开始。

代码:

import javax.swing.JFrame;

public class Launcher extends JFrame {
    private static final long serialVersionUID = 1L;

    public static void main(String[] args) {
        new Launcher().setVisible(true);
        System.out.println("Started Launcher...");
    }
    private Launcher() {
        super("DevCity13 - Launcher (Alpha)");
        setSize(600, 600);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

2 个答案:

答案 0 :(得分:3)

您始终可以显示自己的控制台,该控制台输出写入System.out的内容:

enter image description here

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class Launcher extends JFrame {
    private static final long serialVersionUID = 1L;

    private static class Console {
        private final JFrame frame;

        public Console() {
            frame = new JFrame();
            final JTextArea textArea = new JTextArea(24, 80);
            textArea.setBackground(Color.BLACK);
            textArea.setForeground(Color.LIGHT_GRAY);
            textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
            System.setOut(new PrintStream(new OutputStream() {

                @Override
                public void write(int b) throws IOException {
                    textArea.append(String.valueOf((char) b));
                }
            }));
            frame.add(textArea);
        }

        public void init() {
            frame.pack();
            frame.setVisible(true);
        }

        public JFrame getFrame() {
            return frame;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Console console = new Console();
                console.init();
                Launcher launcher = new Launcher();
                launcher.setVisible(true);
                console.getFrame().setLocation(
                        launcher.getX() + launcher.getWidth()
                                + launcher.getInsets().right, launcher.getY());
                System.out.println("Started Launcher...");
            }
        });
    }

    private Launcher() {
        super("DevCity13 - Launcher (Alpha)");
        setSize(600, 600);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

答案 1 :(得分:0)

您只需在运行.jar时启用Java控制台。为此,请按照官方文档here上的步骤操作。它可能会根据您的操作系统而改变一点,但这就是想法。