本篇為「簡單記事本」系列第三部分,著重於 動作事件處理、尋找/替換對話框 以及 字型設定對話框 的實作細節。程式碼展示了如何整理選單、右鍵選單與工具列的事件分派,並實作模態對話框以提供進階編輯功能。
actionPerformed(ActionEvent e) 方法作為中央分派器,透過 e.getSource() 判斷觸發元件,再呼叫對應的處理方法:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jMenuFileCut || e.getSource() == jMenuMouseCut) {
FileCut(e);
} else if (e.getSource() == jMenuFileCopy || e.getSource() == jMenuMouseCopy) {
FileCopy(e);
}
// ... 其他剪貼簿、查找、字型、顏色、關於等動作
}
此設計將選單項目(JMenuItem)與右鍵選單項目共用同一處理邏輯,減少重複程式碼。
Frame1)Frame1 繼承 JDialog,實作 ActionListener,包含以下元件:
jTextField1)、替換內容(jTextField2)JCheckBox)、搜尋方向(向上/向下 JRadioButton)關鍵演算法(find() 方法):
public void find() {
String text1 = jTextField1.getText();
if (check) text1 = text1.toLowerCase(); // 大小寫處理
int start = jTextArea1.getSelectionStart();
int end = jTextArea1.getSelectionEnd();
if (teams[0].isSelected()) { // 向上搜尋
String before = findstr.substring(0, start);
int index = before.lastIndexOf(text1);
if (index != -1) {
jTextArea1.select(index, index + text1.length());
} else {
showNotFoundDialog(text1);
}
} else { // 向下搜尋
int index = findstr.indexOf(text1, end);
if (index != -1) {
jTextArea1.select(index, index + text1.length());
} else {
showNotFoundDialog(text1);
}
}
}
replace() 方法則針對已選取文字執行 replaceRange()。
Bfont)Bfont 同樣繼承 JDialog,提供三個 JList 分別選擇字體、字型、大小,並即時預覽:
Font.PLAIN、ITALIC、BOLD、BOLD|ITALIC)滑鼠點選列表項目時,更新對應文字欄位與內部變數(ziti、zixing、daxiao),按下「確定」呼叫 sfont() 套用至主文字區:
void sfont() {
jTextArea1.setFont(new Font(ziti, zixing, daxiao));
}
程式大量使用內部類別實作 ActionListener 適配器(如 File_new_actionAdapter),將事件轉發至主類別的具體處理方法,符合「命令模式」精神,利於維護。
此部分展示了 Swing 應用中常見的模態對話框設計、事件集中分派、文字搜尋演算法與字型屬性動態套用技巧,是建構桌面編輯器的實用參考。