本文來自:http://blog.csdn.net/hellogv/ ,轉載必須註明出處!
首先先給出本例的:
首先,需要說明一下LWUIT的控制項:
LWUIT的控制項,可以算是做得很全,他的設計模式跟J2SE有點類似,而做過J2ME的人要掌握也不需要長時間。LWUIT的控制項,是原來進階控制項與低級控制項的集合,並加入了更多元素,因此你可以在用進階控制項的同時,很自然地實現低級控制項的功能。例如本文中的繪圖功能,就是如此!
在本例中,依然使用大家熟悉的void paint(Graphics g)
函數,作為繪圖的主體,然而paint的“上司”(繪圖類)並不再是繼承Canvas,而是繼承Component,並且繼承Component之後要這
樣被調用:form.addComponent(BorderLayout.CENTER, new Painting());//Painting就是“上司”。可見,在LWUIT裡,已經沒低級控制項這個概念,但是有這個用法-----傳統的繪圖類也作為控制項類,被調用了。或許,你想用回原來的javax.microedition.lcdui.Graphics,但是lcdui的Graphics和Display 與 LWUIT的Graphics和Display不相容(LWUIT多了很多方法),因此“新歡舊愛不能兼得”!
OK,先給出調用繪圖功能的代碼:
- private class ButtonActionListener implements ActionListener {
- public void actionPerformed(ActionEvent evt) {
- String sel_button=((Button)(evt.getSource())).getText();//取得所選按鈕的名稱
- if(sel_button.equals("Image 1"))
- new AnimationDemo().form.show();
- else if(sel_button.equals("Image 2"))
- new PaintingDemo().form.show();
- }
- }
接著再給出繪圖功能實現的代碼:
- /*
- * Copyright ?2008 Sun Microsystems, Inc. All rights reserved.
- * Use is subject to license terms.
- *
- */
- package com.sun.lwuit.uidemo;
- import com.sun.lwuit.Command;
- import com.sun.lwuit.Component;
- import com.sun.lwuit.Form;
- import com.sun.lwuit.Graphics;
- import com.sun.lwuit.events.ActionEvent;
- import com.sun.lwuit.events.ActionListener;
- import com.sun.lwuit.layouts.BorderLayout;
- /**
- * Demonstrates simple animation both static and manual
- *
- * @author Shai Almog
- */
- public class PaintingDemo extends Form implements ActionListener {
- public Form form = new Form("PaintingDemo");
- private Command backCommand = new Command("Back", 1);
- private Command nextCommand = new Command("next", 2);
- PaintingDemo()
- {
- form.addCommand(backCommand);
- form.addCommand(nextCommand);
- form.setCommandListener(this);
- form.setLayout(new BorderLayout());
- form.addComponent(BorderLayout.CENTER, new Painting());
- }
- public class Painting extends Component{
- private int w;
- public void paint(Graphics g) {
- g.setColor(0x000000);
- g.fillRect(0, 0, this.getWidth(), this.getHeight());
- w = getWidth();
- drawSqrt1(g);
- g.setColor(0xffffff);
- g.drawString("hellogv", 12, 33);
- }
- private void drawSqrt1(Graphics g) {
- long start = System.currentTimeMillis();
- int centerY1 = 50;
- //繪製X軸
- //設定繪圖顏色為藍色
- g.setColor(0x0000FF);
- g.drawLine(0, centerY1, w, centerY1);
- //設定繪圖顏色為白色
- g.setColor(0xFFFFFF);
- int oldX = 0;
- int oldY1 = centerY1;
- int y1;
- for(int i=1;i<w;i++) {
- // 放大3倍
- y1 = centerY1 - (int)(3*Math.sqrt(i));
- g.drawLine(oldX, oldY1, i, y1);
- oldX = i;
- oldY1 = y1;
- }
- long time = System.currentTimeMillis() - start;
- System.out.println("drawSqrt1 Runtime: " + time);
- }
- }
- public void actionPerformed(ActionEvent arg0) {
- if(arg0.getCommand()==backCommand)
- {
- UIDemoMIDlet.backToMainMenu();
- }
- else if(arg0.getCommand()==nextCommand)
- {
-
- }
- }
- }
OK,還是那句,希望大家多多支援LWUIT,讓它可以做得更加好!