JTextPane เป็นส่วนขยายของ JEditorPane ให้คุณสมบัติประมวลผลข้อความ เช่น ฟอนต์, สไตล์ข้อความ, สี ใช้สำหรับงานประมวลผลข้อความหนัก ในขณะที่ JEditorPane รองรับการแสดง/แก้ไข HTML และ RTF และขยายได้โดยสร้าง EditorKit เอง
JTextPane
- JTextPane เป็นคลาสย่อยของ JEditorPane
- JTextPane ใช้สำหรับเอกสารที่มีสไตล์ พร้อม ภาพฝัง (embedded images) และคอมโพเนนต์
- JTextPane เป็นคอมโพเนนต์ข้อความที่ทำเครื่องหมายด้วยแอตทริบิวต์ที่แสดงเป็นกราฟิก ใช้ DefaultStyledDocument เป็นโมเดลเริ่มต้น
- เมธอดสำคัญ: addStyle(), getCharacterAttributes(), getStyledDocument(), setDocument(), setEditorKit(), setStyledDocument()
ตัวอย่าง JTextPane
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
- JEditorPane เป็นชนิดของพื้นที่ข้อความ แสดงรูปแบบข้อความหลากหลาย
- ค่าเริ่มต้นรองรับ HTML และ RTF (Rich Text Format) สร้าง EditorKit เองได้สำหรับ content type เฉพาะ
- ใช้ setContentType() เลือกเอกสารที่จะแสดง และ setEditorKit() ตั้งค่า Editor แบบกำหนดเอง
ตัวอย่าง JEditorPane
import javax.swing.*;
public class JEditorPaneTest extends JFrame {
public JEditorPaneTest() {
setTitle("JEditorPane Test");
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setText("Java
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.
");
setSize(350, 275);
setContentPane(editorPane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] a) {
new JEditorPaneTest();
}
}
ผลลัพธ์
