首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Eclipse 3.0 插件開發實戰:打造天氣預報與郵件監控專屬工具欄

     編輯:Java 相關知識

前言:Eclipse 即你的專屬工作台

Eclipse 的插件架構讓開發者能將任何想法轉化為 IDE 內建功能。本文完整示範兩個插件的從零建構:天氣預報(網頁擷取 + JEditorPane 渲染 HTML)與 郵件快速監控(JavaMail POP3 + 關鍵字過濾),涵蓋 plugin.xml 宣告、Action 類別、Visual Editor 視窗設計、第三方 JAR 打包發布全流程。

插件專案建立基礎

  1. File → New → Other → Plug-in Project,專案名 myplugin。
  2. 選擇 Hello, World 模板 產生基礎 Action 與選單結構。
  3. 以 Runtime Workbench 執行驗證:選單出現、彈出對話框即成功。

Plug-in Project 精靈

Hello World 對話框

插件一:天氣預報

1. 修改 plugin.xml 定義中文選單

<actionSet label="Sample Action Set" visible="true" id="myplugin.actionSet">
  <menu label="我的空間" id="sampleMenu">
    <separator name="sampleGroup"/>
  </menu>
  <action label="天氣預報" icon="icons/sample.gif" class="myplugin.actions.SampleAction"
          menubarPath="sampleMenu/sampleGroup" toolbarPath="sampleGroup" id="myplugin.actions.SampleAction"/>
</actionSet>

中文選單效果

2. 使用 Visual Editor 設計 WeatherDialog

  • 右鍵套件 → New → Other → Visual Class,父類別 javax.swing.JDialog,類名 WeatherDialog。
  • 拖入 JEditorPane 佔滿客戶區,設定 contentType="text/html"。

Visual Class 精靈

JEditorPane 設計

3. 核心邏輯:抓取新浪天氣 HTML 片段直接渲染

public class WeatherDialog extends JDialog {
    private JEditorPane editorPane;
    public WeatherDialog(String city) {
        this.city = city; initialize();
    }
    private void initialize() {
        setContentPane(getEditorPane());
        try {
            URL url = new URL("https://weather.news.sina.com.cn/cgi-bin/figureWeather/simpleSearch.cgi?city=" + city);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder html = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) html.append(line).append("\n");
            in.close();
            // 擷取 ... 區段
            String body = html.substring(html.indexOf("") + 5);
            editorPane.setText(body);
        } catch (Exception e) { e.printStackTrace(); }
        setTitle("天氣預報"); setSize(400, 300);
    }
    private JEditorPane getEditorPane() {
        if (editorPane == null) { editorPane = new JEditorPane(); editorPane.setContentType("text/html"); }
        return editorPane;
    }
}

4. Action 呼叫對話框

public void run(IAction action) {
    new WeatherDialog("北京").show(); // 或上海、廣州等
}

天氣對話框初版

最終天氣預報效果

插件二:郵件快速監控

1. 新增選單項目

<action label="郵件信息" icon="icons/sample.gif" class="myplugin.actions.MailAction"
        menubarPath="sampleMenu/sampleGroup" toolbarPath="sampleGroup" id="myplugin.actions.MailAction"/>

2. 設定類別 MailConfig

public class MailConfig {
    String popServer, popUser, popPassword;
    String[] strFrom;    // 寄件人關鍵字
    String[] strSubject; // 主旨關鍵字
    boolean isViewContent = false;
    // getter/setter 略
}

3. MailDialog:連接 POP3、過濾、JTextPane 顯示

public class MailDialog extends JDialog {
    private JTextPane textPane;
    private MailConfig[] configs;
    public MailDialog(MailConfig[] configs) { this.configs = configs; initialize(); }
    private void initialize() {
        setContentPane(getTextPane());
        textPane.setText(getAllMailInfo());
        setTitle("郵件信息"); setSize(400, 300);
    }
    private String getAllMailInfo() {
        StringBuilder all = new StringBuilder();
        for (MailConfig mc : configs) all.append(getMailInfo(mc));
        return all.length() == 0 ? "未檢測到相關新郵件!" : all.toString();
    }
    private String getMailInfo(MailConfig mc) {
        StringBuilder info = new StringBuilder();
        Store store = null; Folder folder = null;
        try {
            Session session = Session.getDefaultInstance(System.getProperties(), null);
            store = session.getStore("pop3");
            store.connect(mc.getPopServer(), mc.getPopUser(), mc.getPopPassword());
            folder = store.getDefaultFolder().getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] msgs = folder.getMessages();
            for (Message msg : msgs) {
                String from = ((InternetAddress)msg.getFrom()[0]).getPersonal();
                if (from == null) from = ((InternetAddress)msg.getFrom()[0]).getAddress();
                String subject = msg.getSubject();
                if (match(from, mc.getStrFrom()) || match(subject, mc.getStrSubject())) {
                    info.append("發件人: ").append(from).append("\n")
                        .append("主旨: ").append(subject).append("\n")
                        .append("時間: ").append(msg.getSentDate()).append("\n");
                    if (mc.isViewContent()) info.append(msg.getContent()).append("\n");
                    info.append("------------------------------------\n");
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
        finally { closeQuietly(folder); closeQuietly(store); }
        return info.toString();
    }
    private boolean match(String target, String[] keys) {
        if (keys == null) return true;
        if (target == null) return false;
        for (String k : keys) if (target.indexOf(k) >= 0) return true;
        return false;
    }
    // getTextPane, closeQuietly 略
}

4. MailAction 組裝配置並啟動

public void run(IAction action) {
    MailConfig mc = new MailConfig();
    mc.setPopServer("pop.example.com");
    mc.setPopUser("user"); mc.setPopPassword("pwd");
    mc.setStrFrom(new String[]{"boss", "alert"});
    mc.setStrSubject(new String[]{"urgent", "release"});
    new MailDialog(new MailConfig[]{mc}).show();
}

打包發布與安裝

  1. plugin.xml runtime 區段宣告 myplugin.jar、lib/javaMail.jar、lib/activation.jar 並 <export name="*"/>。
  2. File → Export → Plug-in Development → Deployable plug-ins and fragments 導出。
  3. 3. 解壓至 Eclipse plugins/ 目錄或使用 Help → Software Updates 安裝。 4. 重啟 Eclipse,選單欄出現「我的空間 → 天氣預報 / 郵件信息」。

郵件對話框設計

擴展靈感

  • 將郵件帳號、城市設定外部化為 .properties 或 Preference Store。
  • 加入定時器自動輪詢,彈出通知提醒(Notification API)。
  • 整合 Eclipse Media Player 插件播放音樂、俄羅斯方塊 小遊戲放鬆。
  • 探索 Eclipse Plugin Central 發現更多創意插件。

結語

兩個插件、幾百行代碼,即讓 Eclipse 搭載即時天氣與郵件監控。這正是「一切皆插件」的魅力:你的 IDE,你做主。動手打造屬於你的高效工作環境吧!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved