domingo, 21 de setembro de 2008

JAVA2D

Estudando mais um pouco sobre JAVA2D, resolvi fazer um programa bem simples para testar a utilização da classe GeneralPath. Como aplicação resolvi implementar o gráfico da função Seno.

Abaixo segue o código fonte:


package com.deitel.graphics2d;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.GraphicAttribute;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

public class Trigonometria extends JFrame
{
final int FRAME_WIDTH = 400, FRAME_HEIGHT = 300;

public Trigonometria()
{
super("Trigonometria");

setSize(FRAME_WIDTH, FRAME_HEIGHT);
setVisible(true);
}

@Override
public void paint( Graphics g )
{
Graphics2D g2d = (Graphics2D)g;
super.paint(g2d);

GeneralPath gp = new GeneralPath();
Float w = 350f, h = 200f;

Point2D.Float newZero = new Point2D.Float((FRAME_WIDTH - w)/2, (FRAME_HEIGHT - h)/2);

g2d.setColor( new Color(255,255,255) );
g2d.fill( new Rectangle2D.Float(newZero.x, newZero.y, w, h) );

// drawing x axis
g2d.setColor( new Color( 0, 0, 0 ));
g2d.draw( new Line2D.Float( newZero.x, h / 2 + newZero.y, newZero.x + w, h / 2 + newZero.y ) );

// starting to draw sin function
double y = 0.0; // used to draw
double x = 0.0; // used to calc

// initial point
//gp.moveTo(newZero.x, h / 2 + newZero.y);
double f = 100;
while (x <= (2 * Math.PI + 0.1))
{
y = Math.sin(x);

if (x == 0.0)
gp.moveTo( (x * f / 2 + newZero.x) , (y * -f / 2 + ((newZero.y + h / 2))) );
else
gp.lineTo( (x * f / 2 + newZero.x) , (y * -f / 2 + ((newZero.y + h / 2))) );

x += 0.1;
}
//gp.closePath();

g2d.setColor( new Color(0,0,255) );
g2d.draw( gp );

}

public static void main(String[] args)
{
Trigonometria app = new Trigonometria();
}
}


E abaixo a saída do programa:

Nenhum comentário:

Postar um comentário