| 特性 | JTextField (文本框) | JTextArea (文本區) |
|---|---|---|
| 行數 | 單行 | 多行 |
| 預設觸發事件 | Enter 鍵觸發 ActionEvent | 無預設事件,需搭配按鈕 |
| 常用場景 | 搜尋框、表單單行輸入 | 日誌顯示、多行編輯、程式碼輸入 |
| 捲動支援 | 不需 | 需包裹於 JScrollPane |
getText() / setText(String):取得/設定內容setEditable(false):設為唯讀setHorizontalAlignment(JTextField.CENTER):置中對齊addActionListener(ActionListener):監聽 Enter 確認append(String):尾部追加(高效,不重繪全文)insert(String, int) / replaceRange(String, int, int):插入/取代指定位置setLineWrap(true) / setWrapStyleWord(true):自動換行與單字換行new JScrollPane(textArea):加入捲動條使用者在文本區輸入整數(空白/換行分隔),點擊按鈕計算總和顯示於文本框。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;
public class SumCalculator extends JFrame implements ActionListener {
private JTextArea inputArea;
private JTextField resultField;
private JButton btnSum, btnClear;
public SumCalculator() {
setTitle("整數加總器");
setLayout(new BorderLayout(5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
inputArea = new JTextArea(5, 20);
inputArea.setLineWrap(true);
add(new JScrollPane(inputArea), BorderLayout.CENTER);
JPanel bottom = new JPanel(new FlowLayout(FlowLayout.LEFT));
resultField = new JTextField(15);
resultField.setEditable(false);
btnSum = new JButton("計算總和");
btnClear = new JButton("清除");
btnSum.addActionListener(this);
btnClear.addActionListener(this);
bottom.add(new JLabel("總和:"));
bottom.add(resultField);
bottom.add(btnSum);
bottom.add(btnClear);
add(bottom, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSum) {
String text = inputArea.getText();
StringTokenizer st = new StringTokenizer(text); // 預設分隔:空白、換行、Tab
int sum = 0;
while (st.hasMoreTokens()) {
try {
sum += Integer.parseInt(st.nextToken());
} catch (NumberFormatException ex) {
// 忽略非整數
}
}
resultField.setText(String.valueOf(sum));
} else if (e.getSource() == btnClear) {
inputArea.setText("");
resultField.setText("");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SumCalculator().setVisible(true));
}
}
輸入起始、結束值與因子,列出範圍內所有倍數。
// 關鍵佈局片段
JPanel panel1 = new JPanel(new GridLayout(1, 6));
panel1.add(new JLabel("起始數", JLabel.RIGHT)); panel1.add(startField);
panel1.add(new JLabel("結束數", JLabel.RIGHT)); panel1.add(endField);
panel1.add(new JLabel("因子", JLabel.RIGHT)); panel1.add(factorField);
JPanel panel2 = new JPanel(new GridLayout(1, 4));
panel2.add(new JLabel("計算結果:", JLabel.RIGHT));
panel2.add(new JScrollPane(resultArea));
panel2.add(new JLabel()); // 佔位
panel2.add(btnCompute);
Container cp = getContentPane();
cp.setLayout(new GridLayout(3, 1));
cp.add(new JLabel("倍數查找器", JLabel.CENTER));
cp.add(panel1);
cp.add(panel2);
繼承自 JTextField,差別在於:
getPassword() 回傳 char[] 而非 String,使用後應手動清空陣列(Arrays.fill),降低記憶體殘留風險。setEchoChar('*') 設定遮罩字元(預設即為 *)。掌握 JTextField 與 JTextArea 的差異、事件模型與常用 API,是建立友善 Swing 介面的基礎。善用 JScrollPane、Document 過濾器與格式化文本框(JFormattedTextField)可進一步提升使用者體驗。