Java程式從JTextPane獲取文字並在控制檯顯示


在本文中,我們將學習如何從JTextPane中獲取文字,並在Java中將其顯示在控制檯。我們將使用getText()方法檢索文字並在控制檯中顯示它。此外,我們將使用SimpleAttributeSet應用簡單的文字樣式,例如斜體顏色,以演示如何在GUI中管理帶樣式的文字。

從JTextPane獲取文字的步驟

以下是使用Java從JTextPane獲取文字並在控制檯中顯示的步驟:

  • 首先,我們將建立一個JFrame作為GUI的主視窗。
  • 我們將為框架設定預設的關閉操作,以確保在關閉視窗時應用程式關閉。
  • 建立一個JTextPane元件,用於儲存文字。
  • 使用SimpleAttributeSet應用文字樣式,例如斜體、藍色和白色背景,使用StyleConstants。
  • 使用setText()方法在JTextPane中設定文字,將文字“This is our demo text! We are displaying the text in the console.”插入文字窗格。
  • 使用getText()方法從JTextPane獲取文字,並將其列印到控制檯。
  • 新增滾動窗格並將JTextPane包裝在JScrollPane中,以便在必要時允許滾動,並將其新增到框架中。
  • 顯示框架,我們將使用setSize(550, 300)設定框架的大小,並使用setVisible(true)使其可見以顯示視窗。

Java程式從JTextPane獲取文字

以下是獲取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);
   }
}

輸出

文字將顯示在控制檯上:

程式碼解釋

在此程式中,建立了一個JTextPane來顯示和設定文字樣式。使用setText()方法將文字設定為“This is our demo text! We are displaying the text in the console.”。要檢索並在控制檯中顯示此文字,我們使用getText()方法並列印結果。SimpleAttributeSet用於設定文字樣式,包括藍色、斜體和白色背景。然後將文字窗格包裝在JScrollPane中,並新增到JFrame中,以便在視窗中顯示。

更新於:2024年10月23日

652 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告