Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JFrame/JPanel中可视化控制台java_Java_Swing_Console_Jtextarea_Jtextcomponent - Fatal编程技术网

如何在JFrame/JPanel中可视化控制台java

如何在JFrame/JPanel中可视化控制台java,java,swing,console,jtextarea,jtextcomponent,Java,Swing,Console,Jtextarea,Jtextcomponent,我使用Swing库编写了一个Java程序。 现在,我想将我的控制台输出重定向到JFrame或JPanel中。一旦您拥有了JFrame或JPanel,请向其添加一个文本字段 JTextArea是一个不错的选择,因为它有多行。 添加后,您可以.append('text')到它,而不是写入System.out.print() 您需要创建一个OutputStream,将输出重新定向到文本区域,并实现OutputStream接口的所有必要方法,然后在主程序中,将标准输出重定向到此流中。我曾在我的一个程序中

我使用Swing库编写了一个Java程序。
现在,我想将我的控制台输出重定向到JFrame或JPanel中。

一旦您拥有了
JFrame
JPanel
,请向其添加一个文本字段

JTextArea
是一个不错的选择,因为它有多行。 添加后,您可以
.append('text')到它,而不是写入
System.out.print()


您需要创建一个OutputStream,将输出重新定向到文本区域,并实现OutputStream接口的所有必要方法,然后在主程序中,将标准输出重定向到此流中。我曾在我的一个程序中使用过类似的内容:

import java.io.IOException;
import java.io.OutputStream;

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

public class TextAreaOutputStream extends OutputStream {

   private final JTextArea textArea;
   private final StringBuilder sb = new StringBuilder();
   private String title;

   public TextAreaOutputStream(final JTextArea textArea, String title) {
      this.textArea = textArea;
      this.title = title;
      sb.append(title + "> ");
   }

   @Override
   public void flush() {
   }

   @Override
   public void close() {
   }

   @Override
   public void write(int b) throws IOException {

      if (b == '\r')
         return;

      if (b == '\n') {
         final String text = sb.toString() + "\n";
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               textArea.append(text);
            }
         });
         sb.setLength(0);
         sb.append(title + "> ");
         return;
      }

      sb.append((char) b);
   }
}
您可以通过以下方式进行演示:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintStream;
import javax.swing.*;

@SuppressWarnings("serial")
public class TextAreaOutputStreamTest extends JPanel {

   private JTextArea textArea = new JTextArea(15, 30);
   private TextAreaOutputStream taOutputStream = new TextAreaOutputStream(
         textArea, "Test");

   public TextAreaOutputStreamTest() {
      setLayout(new BorderLayout());
      add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
      System.setOut(new PrintStream(taOutputStream));

      int timerDelay = 1000;
      new Timer(timerDelay , new ActionListener() {
         int count = 0;
         @Override
         public void actionPerformed(ActionEvent arg0) {

            // though this outputs via System.out.println, it actually displays
            // in the JTextArea:
            System.out.println("Count is now: " + count + " seconds");
            count++;
         }
      }).start();
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Test");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new TextAreaOutputStreamTest());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

我知道我迟到了,但对于那些正在寻找更好、更简洁答案的人来说,我让这个巫婆结合了两个自定义类

Console.java

public class Console {
    final JFrame frame = new JFrame("CONSOLE");
    ColorPane textPane;
    JScrollPane scroll;

    public Console() throws Exception {
        textPane = new ColorPane();
        textPane.setPreferredSize(new Dimension(525, 600));
        textPane.setFont(new Font("Lucida Console", Font.BOLD, 12));
        scroll = new JScrollPane(textPane);
        textPane.setBackground(Color.BLACK);

        scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

        textPane.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                scrollToBottom(scroll);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {

            }

            @Override
            public void changedUpdate(DocumentEvent e) {

            }
        });

        //Add textPane in to middle panel
        frame.add(scroll);
        frame.setSize(100, 600);
        frame.pack();
        frame.setVisible(false);
        redirectOut();

    }

    public PrintStream redirectOut() {
        OutputStream out = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                textPane.append(Color.WHITE, String.valueOf((char) b));
            }
        };
        OutputStream errOut = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                textPane.append(Color.RED, String.valueOf((char) b));
            }
        };
        PrintStream ps = new PrintStream(out);
        PrintStream err = new PrintStream(errOut);

        System.setOut(ps);
        System.setErr(err);
        scrollToBottom(scroll);

        return ps;
    }

    public JFrame getFrame() {
        return frame;
    }

    private void scrollToBottom(JScrollPane scrollPane) {
        JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
        AdjustmentListener downScroller = new AdjustmentListener() {
            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                Adjustable adjustable = e.getAdjustable();
                adjustable.setValue(adjustable.getMaximum());
                verticalBar.removeAdjustmentListener(this);
            }
        };
        verticalBar.addAdjustmentListener(downScroller);
    }
}
及 ColorPane.java

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class ColorPane extends JTextPane {

    public void appendNaive(Color c, String s) { // naive implementation
        // bad: instiantiates a new AttributeSet object on each call
        SimpleAttributeSet aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset, c);

        int len = getText().length();
        setCaretPosition(len); // place caret at the end (with no selection)
        setCharacterAttributes(aset, false);
        replaceSelection(s); // there is no selection, so inserts at caret
    }

    public void append(Color c, String s) { // better implementation--uses
        // StyleContext
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                StyleConstants.Foreground, c);

        int len = getDocument().getLength(); // same value as
        // getText().length();
        setCaretPosition(len); // place caret at the end (with no selection)
        setCharacterAttributes(aset, false);
        replaceSelection(s); // there is no selection, so inserts at caret
    }

    public static boolean isPrime(int n) {
        if (n < 2)
            return false;
        double max = Math.sqrt(n);
        for (int j = 2; j <= max; j += 1)
            if (n % j == 0)
                return false; // j is a factor
        return true;
    }

    public static boolean isPerfectSquare(int n) {
        int j = 1;
        while (j * j < n && j * j > 0)
            j += 1;
        return (j * j == n);
    }

}
导入java.awt.Color;
导入javax.swing.JFrame;
导入javax.swing.JScrollPane;
导入javax.swing.JTextPane;
导入javax.swing.text.AttributeSet;
导入javax.swing.text.SimpleAttributeSet;
导入javax.swing.text.StyleConstants;
导入javax.swing.text.StyleContext;
公共类ColorPane扩展了JTextPane{
public void appendNaive(颜色c,字符串s){//naive实现
//错误:在每次调用中设置一个新的AttributeSet对象
SimpleAttributeSet aset=新的SimpleAttributeSet();
setForeground(aset,c);
int len=getText().length();
setCaretPosition(len);//将插入符号放在末尾(无选择)
setCharacterAttributes(aset,false);
replaceSelection(s);//没有选择,因此在插入符号处插入
}
公共void append(颜色c,字符串s){//更好的实现--使用
//样式上下文
StyleContext sc=StyleContext.getDefaultStyleContext();
AttributeSet aset=sc.addAttribute(SimpleAttributeSet.EMPTY,
前景色,c);
int len=getDocument().getLength();//与相同的值
//getText().length();
setCaretPosition(len);//将插入符号放在末尾(无选择)
setCharacterAttributes(aset,false);
replaceSelection(s);//没有选择,因此在插入符号处插入
}
公共静态布尔iPrime(int n){
if(n<2)
返回false;
双倍最大值=数学sqrt(n);
对于(int j=2;j 0)
j+=1;
返回(j*j==n);
}
}
这是我一直在使用的解决方案,它甚至有彩色输出。
顺便说一句,sry代表糟糕的英语(我只有11岁)

那么你到底有什么问题?也许可以将所有这些内容附加到另一个Swing组件(例如
JTextArea
)?好的,我读到了。我还以为还有别的办法呢。因为已经有println了,所以我不想添加新的textarea并附加它们
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class ColorPane extends JTextPane {

    public void appendNaive(Color c, String s) { // naive implementation
        // bad: instiantiates a new AttributeSet object on each call
        SimpleAttributeSet aset = new SimpleAttributeSet();
        StyleConstants.setForeground(aset, c);

        int len = getText().length();
        setCaretPosition(len); // place caret at the end (with no selection)
        setCharacterAttributes(aset, false);
        replaceSelection(s); // there is no selection, so inserts at caret
    }

    public void append(Color c, String s) { // better implementation--uses
        // StyleContext
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                StyleConstants.Foreground, c);

        int len = getDocument().getLength(); // same value as
        // getText().length();
        setCaretPosition(len); // place caret at the end (with no selection)
        setCharacterAttributes(aset, false);
        replaceSelection(s); // there is no selection, so inserts at caret
    }

    public static boolean isPrime(int n) {
        if (n < 2)
            return false;
        double max = Math.sqrt(n);
        for (int j = 2; j <= max; j += 1)
            if (n % j == 0)
                return false; // j is a factor
        return true;
    }

    public static boolean isPerfectSquare(int n) {
        int j = 1;
        while (j * j < n && j * j > 0)
            j += 1;
        return (j * j == n);
    }

}