如何通过drawline方法在canvas中绘制矩形

时间:2011-09-23 13:17:53

标签: java-me midp lcdui

这是我第一次在这里提问。

我是J2ME的新手,现在正在开发一个小应用程序,但是当我想将数据显示到表格中时,我遇到了问题。但是在J2me中不支持表格,因为我知道另一种方式可以代表表格,例如Canvas或CustomItem创建表格。

在Canvas中,我可以画出两行:

-----------------------
|
|
|
|

但我不知道怎样才能得到2行的坐标,如:

                         |
                         |
                         | 
                         |
                         |
--------------------------

两个在整个屏幕上画一个矩形,

我知道drawline方法有4个因子x1,y1,x2,y2。

但是我无法计算x点和y点以在

之上画两条线

我需要你帮我解释或给我示例

我的代码:

package test;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author J2MENewBie
 */
public class TableCanvasExample extends Canvas {
    private int cols=3;
    private int rows =50;
    protected void paint(Graphics g) {
        g.setColor(0x94b2ff);
        g.fillRect(0, 0, this.getWidth(), this.getHeight());
        //draw two lines
        g.setColor(0xf8011e);
        g.drawLine(0, 0, 0, this.getWidth());
        g.drawLine(0, 0, this.getHeight(), 0);

    }

}

package test;

import javax.microedition.lcdui.Display;
import javax.microedition.midlet.*;

/**
 * @author J2ME NewBie
 */
public class TableCanvasMidlet extends MIDlet {
    private TableCanvasExample tbcve;

    public TableCanvasMidlet(){
        tbcve = new TableCanvasExample();
    }
    public void startApp() {
        Display.getDisplay(this).setCurrent(tbcve);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}

P / s:垂直线不是全尺寸我不知道为什么???

谢谢!

1 个答案:

答案 0 :(得分:0)

代码中有太多相同的零 - 尝试使用描述性名称:

    int w = getWidth(), h = getHeight(); // I think this way it's easier to read

    int xLeft = 0, yTop = 0; // descriptive names for zeroes
    // below, replace w - 1 -> w and h - 1 -> h if lines drawn are off-by-one
    int xRight = w - 1, yBottom = h - 1; // names for top - right coordinates

    g.drawLine(xLeft, yTop, xLeft, yBottom); // your left vertical
    g.drawLine(xLeft, yTop, xRight, yTop); // your top horizontal

    g.drawLine(xRight, yTop, xRight, yBottom); // add right vertical
    g.drawLine(xLeft, yBottom, xRight, yBottom); // add bottom horizontal

如果绘制的矩形看起来不像您希望找到上面代码中有错误语义的地方

相关问题