您的位置:首页 > 产品设计 > UI/UE

J2ME GUI实战之五 ----------LWUIT的绘图功能

2008-09-15 10:51 337 查看
本文来自: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,让它可以做得更加好!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: