JTextArea 是 Swing 提供的多行純文字編輯區,支援自動換行、捲動、唯讀模式,是記事本、日誌視窗、SQL 編輯器等桌面應用的基石。本文詳細說明建構子、核心方法、捲動面板整合與完整範例。
| 建構子 | 說明 |
|---|---|
JTextArea() | 空白、無行列限制 |
JTextArea(int rows, int cols) | 指定可見行數與字元寬度(影響 preferred size) |
JTextArea(String text) | 預載文字 |
JTextArea(String text, int rows, int cols) | 文字+行列 |
JTextArea(Document doc) | 使用自訂 Document 模型 |
JTextArea(Document doc, String text, int rows, int cols) | 完整客製化 |
append(String str):在文末追加文字(常用於日誌即時顯示)insert(String str, int pos):在指定位移插入setLineWrap(boolean wrap):啟用/關閉自動換行setWrapStyleWord(boolean word):true 整詞換行,false 強制斷字setEditable(boolean b):設為唯讀(false)或可編輯setFont(Font f):設定字型setRows(int) / setColumns(int):調整可見行列(需重新 revalidate())getLineCount()、getLineStartOffset(int)、getLineEndOffset(int):行資訊JTextArea 本身不具捲動功能,必須放入 JScrollPane:
JTextArea area = new JTextArea(20, 60);
area.setLineWrap(true);
area.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(area,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
VERTICAL_SCROLLBAR_AS_NEEDED:需要時顯示垂直捲軸(預設)VERTICAL_SCROLLBAR_ALWAYS:永遠顯示VERTICAL_SCROLLBAR_NEVER:永不顯示HORIZONTAL_SCROLLBAR_*import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MiniNotepad extends JFrame {
private JTextArea textArea;
private JCheckBox wrapCheck;
public MiniNotepad() {
setTitle("Mini Notepad");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 工具列
JToolBar bar = new JToolBar();
wrapCheck = new JCheckBox("自動換行", true);
wrapCheck.addActionListener(e -> textArea.setLineWrap(wrapCheck.isSelected()));
bar.add(wrapCheck);
JButton clearBtn = new JButton("清空");
clearBtn.addActionListener(e -> textArea.setText(""));
bar.add(clearBtn);
add(bar, BorderLayout.NORTH);
// 文字區 + 捲動
textArea = new JTextArea(25, 80);
textArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
add(new JScrollPane(textArea), BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MiniNotepad().setVisible(true));
}
}
append 內部已優化,但極大量(>10萬行)建議定期 setText("") 或使用 Document 直接操作。setLineWrap(true) + JScrollPane.HORIZONTAL_SCROLLBAR_NEVER。setEditable(false) 仍可選取複製,若需完全鎖定需加 setFocusable(false)。JTextComponent 搭配 Gutter 元件或使用第三方庫(如 RSyntaxTextArea)。掌握 JTextArea + JScrollPane 的黃金搭配、換行模式與唯讀控制,即可快速構建專業級多行文字編輯功能。進階需求(語法高亮、行號、代碼摺疊)建議改用 RSyntaxTextArea 等成熟元件庫。