透過繼承 JApplet 實現一個具備基本加法運算、選單列、顏色選擇器、確認對話框的圖形化計算器,展示 Swing 核心元件佈局、事件處理、對話框使用等基礎技能。
package org.heixue.test.applet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JApplet {
// 選單元件
private JMenu[] menus = { new JMenu("選項"), new JMenu("關於") };
private JMenuItem[] items = {
new JMenuItem("關於"),
new JMenuItem("設定背景色")
};
// 輸入輸出元件
private JButton btnCalculate = new JButton("運算");
private JTextField txtOperand1 = new JTextField("100", 10);
private JTextField txtOperand2 = new JTextField("200", 10);
private JTextField txtResult = new JTextField(20);
private JLabel[] labels = { new JLabel("+"), new JLabel("=") };
// 輔助元件
private JColorChooser colorChooser = new JColorChooser();
private JOptionPane optionPane = new JOptionPane("運算中...");
private ActionListener calculateListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 確認對話框:YES=0, NO=1
int confirm = JOptionPane.showConfirmDialog(
null, "繼續進行運算嗎?", "確定", JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
String op1 = txtOperand1.getText();
String op2 = txtOperand2.getText();
txtResult.setText(calculate(op1, op2));
}
}
};
private ActionListener aboutListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(
null, "作者:黑雪小組", "關於...", JOptionPane.INFORMATION_MESSAGE);
}
};
private ActionListener colorMenuListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 建立顏色選擇對話框,確認時觸發 colorConfirmListener
JColorChooser.createDialog(
null, "背景色...", true, colorChooser, colorConfirmListener, null).setVisible(true);
}
};
private ActionListener colorConfirmListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeBackground(0, colorChooser.getColor());
}
};
@Override
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout()); // 簡單流式佈局
// 建構選單列
menus[0].add(items[1]); // 選項 -> 設定背景色
items[1].addActionListener(colorMenuListener);
menus[1].add(items[0]); // 關於 -> 關於
items[0].addActionListener(aboutListener);
JMenuBar menuBar = new JMenuBar();
for (JMenu menu : menus) menuBar.add(menu);
setJMenuBar(menuBar);
// 加入計算元件:輸入1 + 輸入2 = 結果
cp.add(txtOperand1);
cp.add(labels[0]); // "+"
cp.add(txtOperand2);
cp.add(labels[1]); // "="
cp.add(txtResult);
// 運算按鈕
cp.add(btnCalculate);
btnCalculate.addActionListener(calculateListener);
}
// 背景色變更
private void changeBackground(int type, Object value) {
if (type == 0 && value instanceof Color) {
getContentPane().setBackground((Color) value);
}
}
// 核心加法運算:字串轉整數相加,異常時視為 0
private String calculate(String op1, String op2) {
int val1 = 0, val2 = 0;
try { val1 = Integer.parseInt(op1); } catch (NumberFormatException ignored) {}
try { val2 = Integer.parseInt(op2); } catch (NumberFormatException ignored) {}
return String.valueOf(val1 + val2);
}
// 支援獨立執行 (非 Applet 環境)
public static void main(String[] args) {
JApplet applet = new Calculator();
JFrame frame = new JFrame("計算器");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(260, 140);
applet.init();
applet.start();
frame.setVisible(true);
}
| 技術點 | 實作細節 |
|---|---|
| Applet 生命週期 | init() 初始化、start() 啟動、stop() 停止、destroy() 銷毀 |
| 選單系統 | JMenuBar → JMenu → JMenuItem 階層結構 |
| 模態對話框 | JOptionPane.showConfirmDialog、showMessageDialog、JColorChooser.createDialog |
| 事件處理模型 | 委派事件模型:元件 + addActionListener(ActionListener) |
| 佈局管理 | FlowLayout:依加入順序左右排列,換行自動換行 |
| 跨環境執行 | main() 中嵌入 JFrame 啟動 Applet,便於開發測試 |
這個簡易計算器雖功能基礎,但涵蓋了 Swing 開發的核心要素:元件建構、佈局管理、事件驅動、對話框交互、跨環境部署。掌握這些基石,才能進階構建複雜的桌面應用系統。