⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stockmidlet.java

📁 一个非常全面的手机性能测试项目
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
        whatif.addCommand(BACK_COMMAND);        whatif.addCommand(CALC_COMMAND);        whatif.setCommandListener(new StockCommandListener());        alertList = new List("Alert Menu", Choice.IMPLICIT);        alertList.setTicker(stockTicker);        alertList.append("Add", null);        alertList.append("Remove", null);        alertList.addCommand(BACK_COMMAND);        alertList.setCommandListener(new StockCommandListener());        settingsList = new List("Settings", Choice.IMPLICIT);        settingsList.setTicker(stockTicker);        settingsList.append("Updates", null);        settingsList.append("Add Stock", null);        settingsList.append("Remove Stock", null);        settingsList.addCommand(BACK_COMMAND);        settingsList.setCommandListener(new StockCommandListener());        alertPriceBox = new TextBox("Alert me when stock reaches:", 				    "", 9, TextField.NUMERIC);        alertPriceBox.setTicker(stockTicker);        alertPriceBox.addCommand(DONE_COMMAND);        alertPriceBox.addCommand(BACK_COMMAND);        alertPriceBox.setCommandListener(new StockCommandListener());        updatesForm = new Form("Updates");        updatesChoices = new ChoiceGroup("Update Interval:", Choice.EXCLUSIVE);        updatesChoices.append("Continuous", null); // will be 30 seconds        updatesChoices.append("15 minutes", null); // default for JavaONE        updatesChoices.append("30 minutes", null);        updatesChoices.append("1 hour", null);        updatesChoices.append("3 hours", null);        switch (refresh_interval) {        case 30000:    updatesChoices.setSelectedIndex(0, true);                       break;        case 1800000:  updatesChoices.setSelectedIndex(2, true);                       break;        case 3600000:  updatesChoices.setSelectedIndex(3, true);                       break;        case 10800000: updatesChoices.setSelectedIndex(4, true);                       break;        case 900000:        default:       updatesChoices.setSelectedIndex(1, true);                       break;        }        updatesForm.setTicker(stockTicker);        updatesForm.append(updatesChoices);        updatesForm.addCommand(BACK_COMMAND);        updatesForm.addCommand(DONE_COMMAND);        updatesForm.setCommandListener(new StockCommandListener());        stockSymbolBox = new TextBox("Enter a Stock Symbol:",				     "", 5, TextField.ANY);        stockSymbolBox.setTicker(stockTicker);        stockSymbolBox.addCommand(DONE_COMMAND);        stockSymbolBox.addCommand(BACK_COMMAND);        stockSymbolBox.setCommandListener(new StockCommandListener());        mainMenu();        // Set up and start the timer to refresh the stock quotes        stockRefreshTask = new StockRefreshTask();        stockRefresh = new Timer();        stockRefresh.schedule(stockRefreshTask, 0, refresh_interval);        // FOR JavaONE -- ADD IN A COUPLE DEFAULT STOCKS	/*	addNewStock("MOT");        addNewStock("SUNW");        addNewStock("NOK");        addNewStock("IBM");        addNewStock("AOL");        addNewStock("MSFT");        addNewStock("GM");        addNewStock("FORD");        addNewStock("ORCL");        addNewStock("SEEK");        addNewStock("AT&T");        addNewStock("LU");        addNewStock("HON");        addNewStock("CORL");        addNewStock("NOR");        */    }    /**     * <p>This method is invoked by the application management software when     * the <code>MIDlet</code> no longer needs to be active.  It is a stop     * signal for the <code>MIDlet</code> upon which the <code>MIDlet</code>     * should release any resources which can be re-acquired through the     * <code>startApp<code> method which will be called upon re-activation of     * the <code>MIDlet</code>. The <code>MIDlet</code> enters     * the <code>Paused</code>     * state upon completion of this method.</p>     *     * @see javax.microedition.midlet.MIDlet     */    public void pauseApp() {        // free memory used by these objects        display        = null;        choose         = null;        view           = null;        menu           = null;        alertList      = null;        settingsList   = null;        whatif         = null;        updatesForm    = null;        stockSymbolBox = null;        alertPriceBox  = null;        origPurchPriceField = null;        numSharesField      = null;        stockTicker         = null;        stockRefresh.cancel();        stockRefresh        = null;        stockRefreshTask    = null;        try {            stocks.close();            stocks = null;            alerts.close();            alerts = null;        } catch (Exception e) {}    }    /**     * <p>When the application management software has determined that the     * <code>MIDlet</code> is no longer needed, or perhaps needs to make room     * for a higher priority application in memory, is signals     * the <code>MIDlet</code>     * that it is a candidate to be destroyed by invoking the     * <code>destroyApp(boolean)</code> method. In this case, we need to destroy     * the <code>RecordEnumeration</code>s so that we don't waste their memory     * and close the open <code>RecordStore</code>s.  If the      * <code>RecordStore</code>s     * are empty, then we do not need them to be stored as      * they will be recreated     * on the next invokation of the <code>MIDlet</code> so      * we should delete them.     * At the end of our clean up, we must call <code>notifyDestroyed</code>     * which will inform the application management software that we are done     * cleaning up and have finished our execution and can      * now be safely terminated and     * enters the <code>Destroyed</code> state.</p>     *     * @param unconditional If true when this method is called,      * the <code>MIDlet</code> must     * cleanup and release all resources. If false the <code>MIDlet</code>     * may throw <code>MIDletStateChangeException</code> to indicate it     * does not want to be destroyed at this time.     * @throws <code>MIDletStateChangeException</code>     *         is thrown if the <code>MIDlet</code> wishes to continue to     *         execute (Not enter the <code>Destroyed</code> state). This     *         exception is ignored if <code>unconditional</code> is equal     *         to true.     * @see javax.microedition.midlet.MIDlet     */    public void destroyApp(boolean unconditional) 	throws MIDletStateChangeException {        // If there is no criteria that will keep us from terminating        if (unconditional) {            stockRefresh.cancel();            try {                stocks.close();                alerts.close();                RecordStore settings = 		    RecordStore.openRecordStore("Settings", true);                try {                    settings.setRecord(1, 				       String.valueOf(refresh_interval)				       .getBytes(), 				       0, String.valueOf(refresh_interval)				       .length());                // First time writing to the settings file                } catch (RecordStoreException rse) {                    settings.addRecord(String.valueOf(refresh_interval)				       .getBytes(),				       0, String.valueOf(refresh_interval)				       .length());                }                settings.closeRecordStore();            } catch (Exception e) {		// Ignore exception there is no place to report it            }            notifyDestroyed();	    // Something might make us not want to exit so check it 	    // here before terminating        } else {        }    }    /**     * <p>Calculate the profits in a What If? scenario by the formula:</p>     * <p><type>  Profit = (CurrentPrice - OriginalPurchasePrice)     * * NumberOfShares</type></p>     * <p>First we retrieve the current price of the stock. Then parse the     * original purchase price that the user enters to format it to an     * integer.  Next, retrieve the number of shares from the form that     * the user filled in and then calculate the profits and display a nice     * message (with the result) to the user onscreen.</p>     */    private void calc() {        try {            String s       = stocks.search(stockSymbol);            int currPrice  = Stock.getPrice(s);            int opp        = Stock.makeInt(origPurchPriceField.getString());            int numShares  = 		Integer.valueOf(numSharesField.getString()).intValue();            int profit     = ((currPrice - opp) * numShares);            Form answerForm = new Form(Stock.getName(s) + 				       " " + Stock.getStringPrice(s));            StringBuffer sb = 		new StringBuffer().append("Net profit (loss) is ")		    .append((profit >= 0) ? "$" : "($")		    .append((profit >= 0) ? Stock.convert(profit) :			    "-" + Stock.convert(profit))		    .append((profit >= 0) ? "" : ")")		    .append(" when selling ")		    .append(String.valueOf(numShares))		    .append(" shares at $")		    .append(Stock.convert(currPrice))		    .append(" per share.");            answerForm.append(sb.toString());            answerForm.addCommand(BACK_COMMAND);            answerForm.addCommand(MAIN_MENU_COMMAND);            answerForm.setCommandListener(new StockCommandListener());            display.setCurrent(answerForm);            currentMenu = "AnswerForm";        }        catch (Exception e) {            error("Calculation Failed", 2000);        }    }    /**     * <p>Set an alert for the selected stock at the specified price</p>     *     * @param Sprice String representation of the price of the stock that     *               the user would like an alert for     */    private void setAlert(String Sprice) {        try {            alerts.add((new StringBuffer()                            .append(Stock.getName(stocks.search(stockSymbol)))                            .append(';')                            .append(Stock.makeInt(Sprice))).toString());        } catch (Exception e) {            error("Failed to add alert", 2000);        }    }    /**     * <p>Generate a string (which concatenates all of the stock names and     * prices) which will be used for the <code>Ticker</code>.</p>     *     * @return The ticker string which concatenates all of the stock symbols     *         and prices     */    private String makeTickerString() {        // the ticker tape string        StringBuffer tickerTape = new StringBuffer();        try {            RecordEnumeration re = stocks.enumerateRecords();            while (re.hasNextElement()) {                String theStock = new String(re.nextRecord());                tickerTape.append(Stock.getName(theStock))                          .append(" @ ")                          .append(Stock.getStringPrice(theStock))                          .append("   ");            }        } catch (Exception e) {            return "Error Accessing Database";        }        return tickerTape.toString();    }    /**     * <p>Display a message onscreen for a specified period of time</p>     *     * @param message The message to be displayed     * @param time The delay before the message disappears     */    private void error(String message, int time) {        if (!(display.getCurrent() instanceof Alert)) {            Alert a = new Alert("Error", message, null, AlertType.ERROR);            a.setTimeout(time);            display.setCurrent(a, display.getCurrent());        }    }    /**     * <p>Check the alerts to see if any are registered for tkrSymbol at the     * tkrSymbol's current price</p>     *     * @param tkrSymbol The name of the stock to check for alerts on     */    private void checkAlerts(String tkrSymbol) {        try {            int current_price = Stock.getPrice(stocks.search(tkrSymbol));            RecordEnumeration re = alerts.enumerateRecords(tkrSymbol,						       current_price);            while (re.hasNextElement()) {                String alert_string = new String(re.nextRecord());                int my_price = 		    Integer.valueOf(alert_string				    .substring(alert_string.indexOf(';')+1,					       alert_string.length()))		    .intValue();                Alert a = new Alert(tkrSymbol, "", null, AlertType.ALARM);                StringBuffer sb = new StringBuffer()                                  .append(tkrSymbol)                                  .append(" has reached your price point of $")                                  .append(Stock.convert(my_price))                                  .append(" and currently is trading at $")                                  .append(Stock.getStringPrice(stocks						    .search(tkrSymbol)));                a.setString(sb.toString());                a.setTimeout(Alert.FOREVER);                display.setCurrent(a);                alerts.delete(alert_string);            }        } catch (RecordStoreNotOpenException rsno) {        } catch (RecordStoreException rs) {        }    }    /**

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -