Java 程序从 JTextPane 获取文本并显示在控制台中
java 8object oriented programmingprogramming更新于 2025/9/2 15:40:17
要从 JTextPane 获取文本,请使用 getText() 方法。首先,创建一个文本窗格组件 −
JTextPane textPane = new JTextPane();
现在,获取文本 −
textPane.getText()); 显示在控制台中: System.out.println(textPane.getText());
以下是获取 JTextPane 并在控制台中显示的示例 −
示例
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class SwingDemo {
public static void main(String args[]) throws BadLocationException {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = frame.getContentPane();
JTextPane textPane = new JTextPane();
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.blue);
StyleConstants.setBackground(attributeSet, Color.white);
textPane.setCharacterAttributes(attributeSet, true);
textPane.setText("This is our demo text! We are displaying the text in the console.");
System.out.println(textPane.getText());
JScrollPane scrollPane = new JScrollPane(textPane);
container.add(scrollPane, BorderLayout.CENTER);
frame.setSize(550, 300);
frame.setVisible(true);
}
}
输出

文本将在控制台上显示 −


