在外部jframe中显示java控制台
我制作了一个java应用程序,但现在我需要显示控制台的所有输出(比如异常、println、ecc…)在外部框架中。 我看过一些解决方案,但我不知道我需要做什么
请不要像复制品一样标记这个,因为我找不到任何东西来解决我的问题
我试过这个:
public class Main extends JFrame {
public static void main(String[] args) {
Console console = new Console();
console.init();
Main launcher = new Main();
launcher.setVisible(true);
console.getFrame().setLocation(
launcher.getX() + launcher.getWidth() + launcher.getInsets().right,
launcher.getY());
}
private Main() {
super();
setSize(600, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Console {
final JFrame frame = new JFrame();
public Console() {
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);
System.out.println("Hello world!");
}
public JFrame getFrame() {
return frame;
}
}
但它不起作用
我该怎么办?谢谢
# 1 楼答案
我基于@Razavi的答案,并对其进行了修改,以打印错误:
谢谢
# 2 楼答案
我修复了您的代码并改进了解决方案:
# 3 楼答案
如果您只需要在控制台上显示字符串,这将起作用。也许您需要先将更复杂的数据转换为字符串
我添加了一个名为
printOnConsole(String s)
的函数,将提交的字符串附加到控制台。 因此,在您的应用程序中,例如,您可以使用console.printToConsole("I will be displayed in JFrame Console")
调用此方法 这实际上只适用于字符串,但可以随意添加更复杂的数据结构致意