如何让JTeaxArea显示控制台的信息,并且精确到ms
时间: 2024-04-08 12:34:13 浏览: 8
要在Java中使用JTextArea来显示控制台信息并精确到毫秒,你可以使用以下步骤:
1. 创建一个JFrame窗口和一个JTextArea组件来显示信息。
```java
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ConsoleWindow extends JFrame {
private JTextArea textArea;
public ConsoleWindow() {
setTitle("Console Window");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane);
}
public void appendText(String text) {
textArea.append(text);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
```
2. 创建一个自定义的PrintStream类,将控制台输出重定向到JTextArea中。
```java
import java.io.OutputStream;
import java.io.PrintStream;
public class ConsoleOutputStream extends OutputStream {
private ConsoleWindow window;
public ConsoleOutputStream(ConsoleWindow window) {
this.window = window;
}
@Override
public void write(int b) {
window.appendText(String.valueOf((char) b));
}
}
```
3. 在主程序中使用ConsoleWindow和ConsoleOutputStream来显示控制台信息。
```java
import java.io.PrintStream;
public class Main {
public static void main(String[] args) {
ConsoleWindow consoleWindow = new ConsoleWindow();
consoleWindow.setVisible(true);
PrintStream printStream = new PrintStream(new ConsoleOutputStream(consoleWindow));
System.setOut(printStream);
long startTime = System.currentTimeMillis();
// 执行你的代码
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("执行时间:" + elapsedTime + "ms");
}
}
```
在上面的代码中,我们将System.out重定向到ConsoleOutputStream,ConsoleOutputStream将控制台输出添加到JTextArea中。你可以在需要显示的地方使用System.out.println来输出信息。
注意:以上代码仅为示例,需要根据实际情况调整和扩展。