JavaBean 是 Java 平台上可重複使用的軟體元件模型,遵循特定命名慣例與設計規範。本文將透過一個完整的貸款計算範例,示範如何建立具備屬性編輯器與 Bean 資訊類的標準 JavaBean 元件。
Loan 類別繼承 JPanel 並實作 ActionListener,提供圖形介面讓使用者輸入貸款類型、金額、期數,並自動計算每月應繳金額。程式碼結構如下:
public class Loan extends JPanel implements ActionListener {
// UI 元件宣告
private JLabel lType, lAmount, lmonth, lInstlmnt;
private JTextField tAmount, tmonth, tInstlmnt;
private JList tType;
private JButton submit;
// 貸款利率屬性(符合 JavaBean 規範的 getter/setter)
private String[] interestRates = {"5", "5", "4"};
public String[] getInterestRates() { return interestRates; }
public void setInterestRates(String[] interestRates) { this.interestRates = interestRates; }
// 建構子:初始化介面佈局與事件監聽
public Loan() { ... }
// 事件處理:計算月繳金額
public void actionPerformed(ActionEvent evt) { ... }
}
關鍵設計重點:
實作 PropertyEditor 介面,提供自訂編輯介面讓開發工具(如 BeanBox)能視覺化設定利率屬性:
public class LoanEditor extends JPanel implements PropertyEditor, ActionListener {
// 三種貸款利率的輸入欄位
private JTextField tcar, tpersonal, thouse;
private String[] interestRates = {"", "", ""};
// PropertyEditor 必須實作的核心方法
public Object getValue() { ... } // 取得編輯後的值
public void setValue(Object ctemp) { ... } // 設定待編輯的值
public Component getCustomEditor() { return this; } // 回傳自訂編輯器元件
public boolean supportsCustomEditor() { return true; } // 支援自訂編輯器
// 建構子:建立編輯介面
public LoanEditor() { ... }
}
繼承 SimpleBeanInfo,明確指定 interestRates 屬性使用 LoanEditor 作為屬性編輯器:
public class LoanBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor interestRates = new PropertyDescriptor("interestRates", Loan.class);
interestRates.setPropertyEditorClass(LoanEditor.class);
return new PropertyDescriptor[] { interestRates };
} catch (Exception e) { return null; }
}
}
Manifest 檔案宣告哪些類別是 JavaBean:
Name: Loan.class
Java-Bean: True
Name: LoanEditor.class
Java-Bean: False
Name: LoanBeanInfo.class
Java-Bean: False
編譯後使用 jar 指令打包:
jar cvfm Loan.jar Loan.mft *.class
產生的 Loan.jar 即可在支援 JavaBean 的開發環境中使用。
此範例完整展示 JavaBean 的三大核心要素:
掌握此架構,即可開發出可在視覺化工具中拖拉使用的企業級 Java 元件。