Pie chart : Arc « J2ME « Java Tutorial






Pie chart
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;

public class PieChartMIDlet extends MIDlet implements CommandListener {

  private Command exitCommand;

  public void startApp() {
    Display display = Display.getDisplay(this);

    int[] data = { 10, 20, 30, 40, 20 };
    Displayable d = new PieChartCanvas(data);
    exitCommand = new Command("exit", Command.EXIT, 1);

    d.addCommand(exitCommand);
    d.setCommandListener(this);

    display.setCurrent(d);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command c, Displayable s) {
    notifyDestroyed();
  }
}

class PieChartCanvas extends Canvas {
  int[] data;

  int colors[] = { 0xFF0000, 0xA9E969, 0x00FFFF, 0xC675EC, 0x008800, 0x00C400 };

  public PieChartCanvas(int[] data) {
    this.data = data;
  }

  public void paint(Graphics g) {
    int width = this.getWidth();
    int height = this.getHeight();

    g.setColor(255, 255, 255);
    g.fillRect(0, 0, width, height);

    int sum = 0;
    for (int i = 0; i < data.length; i++) {
      sum += data[i];
    }
    int deltaAngle = 360 * 100 / sum / 100;
    int x = 4;
    int y = 4;
    int diameter;

    if (width > height)
      diameter = height - y * 2;
    else
      diameter = width - x * 2;

    int startAngle = 0;

    for (int i = 0; i < data.length; i++) {
      g.setColor(colors[i]);
      g.fillArc(x, y, diameter, diameter, startAngle, deltaAngle * data[i]);
      startAngle += deltaAngle * data[i];
    }
  }
}








31.27.Arc
31.27.1.Draw arcDraw arc
31.27.2.Fill arcFill arc
31.27.3.Pie chartPie chart
31.27.4.Fill an arc, change new color and fill a rectangleFill an arc, change new color and fill a rectangle