JTextPane เป็นส่วนขยายของ JEditorPane ซึ่งมีคุณสมบัติการประมวลผลคำ เช่น แบบอักษร ลักษณะข้อความ สี และอื่นๆ หากเราต้องประมวลผลข้อความที่ใช้งานหนัก เราสามารถใช้คลาสนี้ในขณะที่ JEditorPane รองรับการแสดง/แก้ไข HTML และ RTF เนื้อหา และสามารถขยายได้โดยการสร้าง EditorKit . ของเราเอง .
JTextPane
- A JTextPane เป็นคลาสย่อยของ JEditorPane .
- A JTextPane ใช้สำหรับเอกสารที่มีสไตล์ที่มี ฝัง รูปภาพ และส่วนประกอบ
- A JTextPane เป็นองค์ประกอบข้อความที่สามารถทำเครื่องหมายด้วยแอตทริบิวต์ที่แสดงแบบกราฟิกและสามารถใช้ DefaultStyledDocument เป็นโมเดลเริ่มต้น
- วิธีการที่สำคัญของ JTextPane คือ addStyle(), getCharacterAttributes(), getStyledDocument(), setDocument(), setEditorKit(), setStyledDocument() และอื่นๆ
ตัวอย่าง
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JTextPaneTest {
public static void main(String args[]) throws BadLocationException {
JFrame frame = new JFrame("JTextPane Test");
Container cp = frame.getContentPane();
JTextPane pane = new JTextPane();
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setBold(set, true);
pane.setCharacterAttributes(set, true);
pane.setText("Welcome to");
set = new SimpleAttributeSet();
StyleConstants.setItalic(set, true);
StyleConstants.setForeground(set, Color.blue);
Document doc = pane.getStyledDocument();
doc.insertString(doc.getLength(), " Tutorials ", set);
set = new SimpleAttributeSet();
StyleConstants.setFontSize(set, 20);
doc.insertString(doc.getLength(), " Point", set);
JScrollPane scrollPane = new JScrollPane(pane);
cp.add(scrollPane, BorderLayout.CENTER);
frame.setSize(375, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} ผลลัพธ์

JEditorPane
- A JEditorPane เป็นพื้นที่ข้อความชนิดหนึ่งที่สามารถแสดงรูปแบบข้อความต่างๆ ได้
- โดยค่าเริ่มต้น JEditorPane รองรับ HTML และ RTF (รูปแบบ Rich Text) เราสามารถสร้างชุดเครื่องมือแก้ไขของเราเองเพื่อจัดการกับเนื้อหาบางประเภทได้
- เราสามารถใช้ setContentType() วิธีการเลือกเอกสารที่เราต้องการแสดงและ setEditorKit() วิธีการตั้งค่าตัวแก้ไขที่กำหนดเองสำหรับ JEditorPane อย่างชัดเจน
ตัวอย่าง
import javax.swing.*;
public class JEditorPaneTest extends JFrame {
public JEditorPaneTest() {
setTitle("JEditorPane Test");
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setText("<h1>Java</h1><p>is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.</p>");
setSize(350, 275);
setContentPane(editorPane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] a) {
new JEditorPaneTest();
}
} ผลลัพธ์
