Algorithm on GeneralPath in Graphics2D

Hie!~Good Day
I am facing this problem for some time but still cannot solve it. I got all the syntax correct (well at least no error during compiling) but still nothing change.
The part that perform this consists of 2 class file, Zoom and Data. In Zoom, it loads the image and display it when the program starts. Data is started when a file is loaded into the program. The file contains the coordinates,which is used to draw lines connecting all the coordinates.
What I did: in Data, I get all the values into 2 public array(xcoor,ycoor). If the xcoor or ycoor is not null, I run the zoom again, like this:
if(xcoor!=null||ycoor!=null)
new Zoom();
in Zoom, actually it already ran once when loaded, so the image is already displayed. I create 2 new arrays (xcoor1,ycoor2) to copy all the value from xcoor and ycoor(just to play safe). then I start draw it. like this:
GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,x1Points.length);
polygon.moveTo(xcoor1[0], ycoor1[0]);
for ( int i = 1; i < xcoor1.length; i++ ) {
polygon.lineTo(xcoor1, ycoor1[i]);
context.draw(polygon);
context is Graphics2D. The compilation into class file is ok. But the GeneralPath is not drawn into the context. What is wrong with this?
P.S. I don't want the topic to be so long so I didn't paste the whole code.

Here is what I did:
if((x == null) || (y == null))
return;
int num = x.length;
path = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
path.moveTo(x[0], y[0]);
for(int i=1; i<num;i++)
path.lineTo(x, y[i]);
g.draw(path);
This code is within a function and after the function call, I call repaint and then my graphic is displayed. It looks to me that the piece of code you showed is ok. Therefore the problem may come from somewhere else. I suggest you check the coordinate array to make sure it contains valid value( at least not all zeros ). Also double check you paintComponent.

Similar Messages

  • Please help with my Graphics2D clipping algorithm

    I'm trying to write a redeye removal function which has the user click on an image to create a Stack of Circle(s) where the pupils are, then "clips" the circle(s) and applys a RasterOp against the pixels inside the clip. I found an example here (http://java.sun.com/mailers/techtips/corejava/2006/tt0923.html) and modified it to fit my needs. (Code below)
    My problem is that it seems like I'm applying the RasterOp filter against the entire source (BufferedImage) and then compositing the result it on top of the source using the alpha channel. This could be a 10MP photo!
    How can I make this more efficient by just applying the RasterOp against the Shape(s) which make up the clip? I tried a couple of ways, but I can't figure it out. Is there a better way to do this?
    [ filterShape is called from public void paintComponent( Graphics g )]
         public void filterShape(Graphics g, Stack<Rectangle> redeyes) {
    //          Create a translucent intermediate image in which we can perform
    //          the soft clipping
              GraphicsConfiguration gc = ((Graphics2D) g).getDeviceConfiguration();
              BufferedImage img = gc.createCompatibleImage(this.getWidth(), this.getHeight(), Transparency.TRANSLUCENT);
              Graphics2D g2 = img.createGraphics();
    //          Clear the image so all pixels have zero alpha
              g2.setComposite(AlphaComposite.Clear);
              g2.fillRect(0, 0, this.getWidth(), this.getHeight());  // sets the background to transparent
    //          Render our clip shape into the image.  Note that we enable
    //          antialiasing to achieve the soft clipping effect.  Try
    //          commenting out the line that enables antialiasing, and
    //          you will see that you end up with the usual hard clipping.
              g2.setComposite(AlphaComposite.Src);
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g2.setColor(Color.WHITE); // sets the mask for opaque
              for(int i=0;i<redeyes.size();i++) {
                   Rectangle r = redeyes.elementAt(i);
                   Ellipse2D.Float circle = new Ellipse2D.Float(r.x, r.y, r.width, r.height);
                   g2.clip((Shape)circle);
              g2.fillRect(0, 0, this.getWidth(), this.getHeight());
    //          Here's the trick... We use SrcAtop, which effectively uses the
    //          alpha value as a coverage value for each pixel stored in the
    //          destination.  For the areas outside our clip shape, the destination
    //          alpha will be zero, so nothing is rendered in those areas.  For
    //          the areas inside our clip shape, the destination alpha will be fully
    //          opaque, so the full color is rendered.  At the edges, the original
    //          antialiasing is carried over to give us the desired soft clipping
    //          effect.
              g2.setComposite(AlphaComposite.SrcAtop);
              BufferedImage clipBI = FotoFix.applyRedeyeFix((BufferedImage)this.image);
              g2.drawImage(clipBI, 0, 0, this.getWidth(), this.getHeight(), null);
              // paint the whole g2 red to see if clip constrains the paint
    //          g2.setColor(Color.RED); // sets the mask for opaque
    //          g2.fillRect(0, 0, this.getWidth(), this.getHeight());
              g2.dispose();
              g.drawImage(img, 0, 0, null);
         }NOTE: The code works for a Stack.size()=1 right now, still debugging to add multiple redeyes to the clip.

    @posiedee 
    Thank you for using HP Support Forum. I have sent you a private message. If you’re unsure how to check your private messages please click here.
    Thank you,
    Omar
    I Work for HP

  • Looking for a 2D Polygon Bevel Algorithm

    I am looking for a graphics algorithm to give two-dimensional polygons a 3D beveled edge look. The polygon should look like as though it is lit from the top-left. This is trivial for rectangular figures, but obviously much more complex for general polygons. The algorithm needs to support any type of polygon, including those with splines or other curved edges, as well as convex figures. Making matters even more complicated, it must also handle texture-filled polygons.
    A Java class that provides this functionality would be perfect. Short of that, an implementation in any language, or even a description of an algorithm, would be helpful.
    I created a java applet to illustrate the problem I am trying to solve - see the source below. This applet with source is also available at
    http://www.keithhilen.com/Java/bevel/
    Keith Hilen
    [email protected]
    Polygons.java :
    import java.applet.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    public class Polygons extends Applet
    Image image;
    int polyWidth = 100;
    int polyHeight = polyWidth;
    int polyOfsX1 = 100;
    int polyOfsY1 = 100;
    int polyOfsX2 = 250;
    int polyOfsY2 = 100;
    int polyOfsX3 = 100;
    int polyOfsY3 = 240;
    int polyOfsX4 = 250;
    int polyOfsY4 = 240;
    Polygon octagon;
    Ellipse2D.Double ellipse;
    GeneralPath ornament;
    BufferedImage imageBuf1, imageBuf2, imageBuf3, imageBuf4;
    public void init()
    image = loadImage("background.jpg");
    createPolygons();
    createImageBufs();
    private Image loadImage(String name)
    MediaTracker tracker = new MediaTracker(this);
    Image image = getImage(getDocumentBase(), name);
    tracker.addImage(image, 0);
    for ( ; ; )
    try { tracker.waitForAll(); } catch (InterruptedException e) { }
    if (tracker.checkAll())
    break;
    return image;
    public void createPolygons()
    double sqrt2 = Math.sqrt(2);
    int m1 = (int) (polyWidth / (2 + sqrt2));
    int m2 = (int) (polyWidth * sqrt2 / (2 + sqrt2));
    octagon = new Polygon();
    octagon.addPoint(-m2/2, -(m1 + m2/2));
    octagon.addPoint(+m2/2, -(m1 + m2/2));
    octagon.addPoint(+(m1 + m2/2), -(m2/2));
    octagon.addPoint(+(m1 + m2/2), +(m2/2));
    octagon.addPoint(+m2/2, +(m1 + m2/2));
    octagon.addPoint(-m2/2, +(m1 + m2/2));
    octagon.addPoint(-(m1 + m2/2), +(m2/2));
    octagon.addPoint(-(m1 + m2/2), -(m2/2));
    ellipse = new Ellipse2D.Double(-polyWidth/2, -polyWidth/2, polyWidth, polyWidth*3/4);
    ornament = new GeneralPath();
    int l = polyWidth/2;
    int m = polyWidth/16;
    int s = polyWidth/32;
    ornament.moveTo(+0+0, -l+0);
    ornament.quadTo(+0+s, -l+0, +0+s, -l+s);
    ornament.quadTo(+m+0, -m+0, l-s, 0-s);
    ornament.quadTo(+l+0, +0-s, l0, +0+0);
    ornament.quadTo(+l+0, +0+s, l-s, 0+s);
    ornament.quadTo(+m+0, m0, +0+s, +l-s);
    ornament.quadTo(+0+s, l-0, 0+0, l0);
    ornament.quadTo(+0-s, l0, +0-s, +l-s);
    ornament.quadTo(-m+0, m0, -l+s, +0+s);
    ornament.quadTo(-l+0, +0+s, -l+0, +0+0);
    ornament.quadTo(-l+0, +0-s, -l+s, +0-s);
    ornament.quadTo(-m+0, -m+0, +0-s, -l+s);
    ornament.quadTo(+0-s, -l+0, -0+0, -l+0);
    public void createImageBufs()
    Graphics2D g2d;
    Composite saveAlpha;
    // Figure 1
    // Create image buf and get context
    imageBuf1 = new BufferedImage(polyWidth, polyHeight,
    BufferedImage.TYPE_INT_ARGB_PRE);
    g2d = (Graphics2D) imageBuf1.getGraphics();
    // Fill with transparent color
    saveAlpha = g2d.getComposite();
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR,
    0.0f));
    g2d.fillRect(0, 0, polyWidth, polyHeight);
    g2d.setComposite(saveAlpha);
    // Draw figure
    g2d.translate(polyWidth/2, polyHeight/2);
    g2d.setClip(octagon);
    g2d.setColor(Color.blue);
    g2d.fillRect(-polyWidth/2, -polyHeight/2, polyWidth, polyHeight);
    // Figure 2
    // Create image buf and get context
    imageBuf2 = new BufferedImage(polyWidth, polyHeight,
    BufferedImage.TYPE_INT_ARGB_PRE);
    g2d = (Graphics2D) imageBuf2.getGraphics();
    // Fill with transparent color
    saveAlpha = g2d.getComposite();
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR,
    0.0f));
    g2d.fillRect(0, 0, polyWidth, polyHeight);
    g2d.setComposite(saveAlpha);
    // Draw figure
    g2d.translate(polyWidth/2, polyHeight/2);
    g2d.setClip(octagon);
    g2d.drawImage(image, -polyWidth/2, -polyWidth/2, null);
    // Figure 3
    // Create image buf and get context
    imageBuf3 = new BufferedImage(polyWidth, polyHeight,
    BufferedImage.TYPE_INT_ARGB_PRE);
    g2d = (Graphics2D) imageBuf3.getGraphics();
    // Fill with transparent color
    saveAlpha = g2d.getComposite();
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
    g2d.fillRect(0, 0, polyWidth, polyHeight);
    g2d.setComposite(saveAlpha);
    // Draw figure
    g2d.translate(polyWidth/2, polyHeight/2);
    g2d.setClip(ellipse);
    g2d.drawImage(image, -polyWidth/2, -polyWidth*5/8, null);
    // Figure 4
    // Create image buf and get context
    imageBuf4 = new BufferedImage(polyWidth, polyHeight, BufferedImage.TYPE_INT_ARGB_PRE);
    g2d = (Graphics2D) imageBuf4.getGraphics();
    // Fill with transparent color
    saveAlpha = g2d.getComposite();
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
    g2d.fillRect(0, 0, polyWidth, polyHeight);
    g2d.setComposite(saveAlpha);
    // Draw figure
    g2d.translate(polyWidth/2, polyHeight/2);
    g2d.setClip(ornament);
    g2d.drawImage(image, -polyWidth/2, -polyWidth/2, null);
    public void paint(Graphics g)
    g.drawImage(imageBuf1, polyOfsX1 - polyWidth/2, polyOfsY1 - polyHeight/2, null);
    g.drawImage(imageBuf2, polyOfsX2 - polyWidth/2, polyOfsY2 - polyHeight/2, null);
    g.drawImage(imageBuf3, polyOfsX3 - polyWidth/2, polyOfsY3 - polyHeight/2, null);
    g.drawImage(imageBuf4, polyOfsX4 - polyWidth/2, polyOfsY4 - polyHeight/2, null);
    Polygons.html :
    <applet
    code=Polygons.class
    name=Polygons
    width=360
    height=300>
    </applet>

    Think you'll be lucky to find anything in the forum on push down automata. Do a search on google, perhaps with the keyword "parser" or "grammer checker" thrown in. There may well be whole books devoted to it!

  • GeneralPath not Filling entire path

    Hi,
    i'm trying to draw a graph using a GeneralPath.
    the problem is that if at the bottom it's not wide enough the top ends
    up lower than it's supposed to.
    Here is a crude example (i just put this together as an
    example)please compile and run this program
    -----------------------PathTest.java----------------------------------
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class PathTest extends JFrame implements ActionListener{
    public PathTest(){
    setSize(400,500);
    setTitle("TestGraph's Frame");
    addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    Container contentPane = getContentPane();
    p = new PathPanel();
    contentPane.add(p,"Center");
    String [] tOrF = {"Fill","Just Draw"};
    JComboBox comb = new JComboBox(tOrF);
    comb.setSelectedIndex(1);
    comb.addActionListener(this);
    contentPane.add(comb,"North");
    public void actionPerformed(ActionEvent evt){
    JComboBox comb = (JComboBox)evt.getSource();
    String f = (String)comb.getSelectedItem();
    if(f.trim().equals("Fill"))
    p.setFill(true);
    else
    p.setFill(false);
    p.repaint();
    public static void main(String [] args){
    JFrame frame = new PathTest();
    frame.show();
    PathPanel p = null;
    class PathPanel extends JPanel{
    boolean fill = true;
    public void setFill(boolean fill){this.fill = fill;}
    public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D)g;
    double [] pixPoints = {365.0,290.0,370.0,89.0,375.0,290.0};
    paintPath(g2d,pixPoints);
    double [] pixPoints1 = {10.0,290,200.0,89.0,299.0,290.00};
    paintPath(g2d,pixPoints1);
    public void paintPath(Graphics2D g2d,double [] pixPoints){
    GeneralPath path = new GeneralPath();
    g2d.drawLine(0,(int)pixPoints[1],this.getWidth(),(int)pixPoints[1]);
    g2d.drawLine(0,89,this.getWidth(),89);
    for(int i =0 ; i < pixPoints.length -1;i +=2){
    double pix [] = {pixPoints[i],pixPoints[i+1]};
    if(i ==0)
    path.moveTo((float)pix[0],(float)pix[1]);
    else
    path.lineTo((int)pix[0],(int)pix[1]);
    path.closePath();
    if(fill)
    g2d.fill(path);
    else
    g2d.draw(path);
    as you see the problem is only if i use g2d.fill and not when i use
    g2d.draw.....
    any help would be greatly appreciated
    Thanks,
    Sol

    OK,
    sorry everybody. i just found out that means something when u post it, so here is the source code in code tags..
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class PathTest extends JFrame implements ActionListener{
        public PathTest(){
            setSize(400,500);
          setTitle("TestGraph's Frame");
          addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
          Container contentPane = getContentPane();
           p = new PathPanel();
          contentPane.add(p,"Center");
          String [] tOrF = {"Fill","Just Draw"};
          JComboBox comb = new JComboBox(tOrF);
          comb.setSelectedIndex(1);
          comb.addActionListener(this);
          contentPane.add(comb,"North");
        public void actionPerformed(ActionEvent evt){
            JComboBox comb  = (JComboBox)evt.getSource();
            String f = (String)comb.getSelectedItem();
            if(f.trim().equals("Fill"))
             p.setFill(true);
            else
             p.setFill(false);
            p.repaint();
        public static void main(String [] args){
            JFrame frame = new PathTest();
            frame.show();
        PathPanel p = null;
    class PathPanel extends JPanel{
        boolean fill = true;
        public void setFill(boolean fill){this.fill = fill;}
        public void paintComponent(Graphics g){
            Graphics2D g2d = (Graphics2D)g;
            double [] pixPoints = {365.0,290.0,370.0,89.0,375.0,290.0};
            paintPath(g2d,pixPoints);
            double [] pixPoints1 = {10.0,290,200.0,89.0,299.0,290.00};
            paintPath(g2d,pixPoints1);
        public void paintPath(Graphics2D g2d,double [] pixPoints){
         GeneralPath path = new GeneralPath();
    g2d.drawLine(0,(int)pixPoints[1],this.getWidth(),(int)pixPoints[1]);
         g2d.drawLine(0,89,this.getWidth(),89);
         for(int i =0 ; i < pixPoints.length -1;i +=2){
            double pix [] = {pixPoints,pixPoints[i+1]};
    if(i ==0)
    path.moveTo((float)pix[0],(float)pix[1]);
    else
    path.lineTo((int)pix[0],(int)pix[1]);
    path.closePath();
    if(fill)
    g2d.fill(path);
    else
    g2d.draw(path);

  • Setting color with Graphics2D on a BufferedImage with IndexColorModel

    I hava a BufferedImage from a GIF, the ColorModel is a IndexColorModel . Since i finally want to write back the modified image to a GIF , i don't want to change the color model, especially my application need to absolutely keep the palette as it is used in the original GIF.
    Then i did create a Graphics2d from this BufferedImage.
    Then i call setColor() and drawString().
    My problem: if I use a color that is not contained in the palette, or if I call drawString() with font antialiasing , which will produce pixels with a color not contained in the palette. How is are these new colors mapped to the palette color?
    Or how can i controll this mapping ?
    Unfortunately I did not found the source code from SunGraphics2D , so that I can see myself what exactly is goning on inside when calling setColor and drawSting und the circumstances described above.
    Any ideas where I can get the source code from ?

    I've just examined some examples and can confirm that the closest color instead of specified is used when you try to draw something on the indexed image. But I was not a success to find out the exact algorithm because of its' native implementation - I can only say it works well.
    I think you want to control the result palette only to keep its' size less then 256 colors. According to described above you should not afraid of palette increasing if you draw on an indexed image (with IndexColorModel). But if you want to draw something with the exact color then you have 2 chances:
    1) Before drawing you can replace (or add if it's possible) any color in a palette with the specified color (which you plan to use for drawing) using your own algorithm.
    2) You can convert your image with indexed color model to for example image with direct color model and then draw anything with any colors. After that you should need to quantize the result image back to an indexed palette with the desired color bit depth.

  • Graph Drawing Algorithms II

    Hi guys,
    I'm researching graph layout algorithms. Most of the packages available don't suit because they require the user to specify a number of nodes and edges between them and then it draws them very prettily.
    Because I want an extension of a Circle class to be drawn and I need it to be drawn on a customised JPanel called Canvas most of these programs aren't suitable. I have the program laying them out itself but atm they look crude and horrible.
    What I'd like is a plug in java program that can assign coordinates and a basic structure to the graph that I entered.
    Thank you very much for reading this far,

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class CircleTest extends JPanel
        CircleModel[] circles;
        CircleModel selectedCircle;
        final int
            PAD  = 20,
            SIZE = 10;
        public CircleTest()
            Point[] cps = { new Point(25,25), new Point(80,60), new Point(35,80) };
            circles = new CircleModel[cps.length];
            circles[0] = new CircleModel(cps[0], 15, Color.green.darker(), Color.cyan);
            circles[1] = new CircleModel(cps[1], 20, Color.red,            Color.orange);
            circles[2] = new CircleModel(cps[2], 15, Color.blue,           Color.magenta);
        protected void paintComponent(Graphics g)
             super.paintComponent(g);
             Graphics2D g2 = (Graphics2D)g;
             g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                 RenderingHints.VALUE_ANTIALIAS_ON);
             double w = getWidth();
             double h = getHeight();
             double xInc = SIZE * (w - 2*PAD) / CircleModel.MAX_X;
             double yInc = SIZE * (h - 2*PAD) / CircleModel.MAX_Y;
             g2.setPaint(new Color(220,200,240));
             // vertical model grid lines
             double x = PAD;
             for(int j = 0; j <= SIZE; j++, x += xInc)
                 g2.draw(new Line2D.Double(x, PAD, x, h-PAD));
             // horizontal model grid lines
             double y = PAD;
             for(int j = 0; j <= SIZE; j++, y += yInc)
                 g2.draw(new Line2D.Double(PAD, y, w-PAD, y));
             double vw = w - 2*PAD;
             double vh = h - 2*PAD;
             for(int j = 0; j < circles.length; j++)
                 CircleModel circle = circles[j];
                 Color color = circle.color;
                 if(circle == selectedCircle)
                     color = circle.selectColor;
                 g2.setPaint(color);
                 Point2D p = circle.getLocation(vw, vh);
                 double[] s = circle.getSize(vw, vh);
                 g2.draw(new Ellipse2D.Double(PAD+p.getX(), PAD+p.getY(), s[0], s[1]));
                 g2.setPaint(Color.red);
                 p = circle.getCenter(vw, vh);
                 g2.fill(new Ellipse2D.Double(PAD+p.getX()-2, PAD+p.getY()-2, 4, 4));
        public void setSelection(CircleModel selected)
            selectedCircle = selected;
            repaint();
        public Rectangle2D getViewRect()
            Rectangle2D.Double r = new Rectangle2D.Double();
            r.x = PAD;
            r.y = PAD;
            r.width  = getWidth()  - 2*PAD;
            r.height = getHeight() - 2*PAD;
            return r;
        public static void main(String[] args)
            CircleTest test = new CircleTest();
            SweepTester sweeper = new SweepTester(test);
            test.addMouseMotionListener(sweeper);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class SweepTester extends MouseMotionAdapter
        CircleTest circleTest;
        CircleModel lastSelection;
        public SweepTester(CircleTest ct)
            circleTest = ct;
        public void mouseMoved(MouseEvent e)
            Point p = e.getPoint();
            boolean haveSelection = false;
            CircleModel[] circles = circleTest.circles;
            Rectangle2D r2 = circleTest.getViewRect();
            for(int j = 0; j < circles.length; j++)
                if(circles[j].contains(p, r2))
                    circleTest.setSelection(circles[j]);
                    lastSelection = circles[j];
                    haveSelection = true;
                    break;
            if(!haveSelection && lastSelection != null)
                lastSelection = null;
                circleTest.setSelection(null);
    class CircleModel
        Point2D center;
        double radius;
        Color color;
        Color selectColor;
        final static int
            MAX_X = 100,
            MAX_Y = 100;
        public CircleModel(Point p, int r, Color c, Color sc)
            center = p;
            radius = r;
            color = c;
            selectColor = sc;
        protected Point2D getLocation(double w, double h)
            Point2D.Double modelLoc = new Point2D.Double();
            modelLoc.x = center.getX() - radius;
            modelLoc.y = center.getY() - radius;
            Point2D viewLoc = modelToView(modelLoc, w, h);
            return viewLoc;
        protected Point2D getCenter(double w, double h)
            return modelToView(center, w, h);
        protected double[] getSize(double w, double h)
            Point2D cp = getCenter(w,h);
            Point2D loc = getLocation(w,h);
            double width  = 2 * (cp.getX() - loc.getX());
            double height = 2 * (cp.getY() - loc.getY());
            return new double[] { width, height };
        private Point2D modelToView(Point2D modelP, double viewWidth, double viewHeight)
            Point2D.Double viewP = new Point2D.Double();
            viewP.x = viewWidth  * modelP.getX() / MAX_X;
            viewP.y = viewHeight * modelP.getY() / MAX_Y;
            return viewP;
        public boolean contains(Point p, Rectangle2D r)
            Point2D loc = getLocation(r.getWidth(), r.getHeight());
            double[] size = getSize(r.getWidth(), r.getHeight());
            Ellipse2D e = new Ellipse2D.Double(r.getX() + loc.getX(),
                                               r.getY() + loc.getY(), size[0], size[1]);
            return e.contains(p);
    }

  • Graphics2D design paradigm

    In Short
    ========
    What is the typical structure for managing and drawing independent 'items' on a panel/canvas within a Graphics2D application?
    In Detail
    =========
    2D graphics drawn on a panel are basically just a bunch of coloured regions that might form some kind of image or picture. (in the most simplistic form anyway)
    But imagine we have a number of shapes we wish to consider to be individual 'items' within that image, which can move around the panel during the course of the application.
    A static/hardcoded drawing routine within the panel's paint() method is not sufficient here since that would just draw the same image each time the panel is repainted and not allow 'movement' of our individual shapes.
    Instead we need to somehow maintain the state of these 'items' in order to preserve their physical appearance (size, shape, colour, etc) and their location on the panel so that as they move around within the panel we know how to redraw them (what they should look like and where they should be). A bunch of POJOs (Plain Old Java Objects) would probably do the trick here.
    My question now is, what is the typical structure of a panel's paint()/repaint() method to dynamically look up all of the individual 'items' that require drawing and then do so as appropriate?
    How is the state for all these 'items' stored and managed?
    What is the common pattern of design for this application scenario?
    I ask because I imagine it must be a very common structure, shared by all Graphics2D applications that involve 'moving' components (such as sprites in a game perhaps).
    Many thanks
    John Senford

    Lots of choices in this area. Some things I've found useful as options:
    1 &#8212; Use java.awt.geom primitives such as Ellipse2D. These will keep the current location and size information, can be drawn, filled and moved easily and transformed with AffineTransform. This is useful for one or a few objects.
    2 &#8212; for more or many objects you can use an array or, if dynamically adding/removing objects, an ArrayList of primitives. Save/store them as "Shape" (interface) types if you have more than one kind, egs, Line2D, Rectangle2D, GeneralPath, Polygon. Run through the array or List and draw/fill each one in your rendering code.
    3 &#8212; for more fine&#8211;grained control over your render objects you can use a data store which can hold anything you want, egs, color, selected color, location, size, speed, text for id/state info, state booleans. Use this object type for your array or list.
    Do all of the changes to your rendering objects/state within event code and let the (graphic components) "paintComponent" method show them according to their current state.

  • Efficient algorithm

    Give me an efficient algorithm to find out the points in the arc.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class ArcPoints extends JPanel
        Arc2D arc;
        Line2D radial;
        Point2D curveLoc;
        boolean showConstruction;
        JLabel label;
        NumberFormat nf;
        public ArcPoints()
            showConstruction = false;
            nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(1);
            Pointer pointer = new Pointer(this);
            addMouseListener(pointer);
            addMouseMotionListener(pointer);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(arc == null)
                initArc();
            g2.draw(arc);
            g2.setPaint(Color.blue);
            g2.draw(radial);
            drawPoint(g2, Color.red, curveLoc.getX(), curveLoc.getY());
            if(showConstruction)
                showConstructionMarkers(g2);
        protected void setRadial(Point p, double theta)
            double cx = arc.getCenterX();
            double cy = arc.getCenterY();
            double x = cx + (arc.getWidth()/2)  * Math.cos(theta);
            double y = cy + (arc.getHeight()/2) * Math.sin(theta);
            radial.setLine(cx, cy, x, y);
            curveLoc.setLocation(x, y);
            label.setText("x = " + nf.format(x) + "    y = " + nf.format(y));
            repaint();
        private void initArc()
            double w = getWidth();
            double h = getHeight();
            double x = w/6;
            double y = h/8;
            double width  = w*2/3;
            double height = h*5/8;
            double start  = 0.0;
            double extent = 300.0;
            int type = Arc2D.OPEN;
            arc = new Arc2D.Double(x, y, width, height, start, extent, type);
            radial = new Line2D.Double();
            curveLoc = new Point2D.Double();
        private void showConstructionMarkers(Graphics2D g2)
            g2.setPaint(Color.orange);
            Rectangle2D r = arc.getFrame();
            g2.draw(r);
            g2.setPaint(Color.green.darker());
            double theta = Math.toRadians(arc.getAngleStart() - arc.getAngleExtent());
            g2.draw(getRadialMarker(theta));
            theta = Math.toRadians(arc.getAngleStart());
            g2.draw(getRadialMarker(theta));
        private void drawPoint(Graphics2D g2, Color color, double x, double y)
            g2.setPaint(color);
            g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
        private Line2D getRadialMarker(double theta)
            Rectangle2D r = arc.getFrame();
            double x = r.getCenterX() + (r.getWidth()/2) * Math.cos(theta);
            double y = r.getCenterY() + (r.getHeight()/2) * Math.sin(theta);
            return new Line2D.Double(r.getCenterX(), r.getCenterY(), x, y);
        private JLabel getLabel()
            label = new JLabel("curve x and y", JLabel.CENTER);
            Dimension d = label.getPreferredSize();
            d.height = 25;
            label.setPreferredSize(d);
            return label;
        public static void main(String[] args)
            ArcPoints arcPoints = new ArcPoints();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(arcPoints);
            f.add(arcPoints.getLabel(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class Pointer extends MouseInputAdapter
        ArcPoints ap;
        public Pointer(ArcPoints ap)
            this.ap = ap;
        public void mousePressed(MouseEvent e)
            ap.showConstruction = !ap.showConstruction;
            ap.repaint();
        public void mouseMoved(MouseEvent e)
            Point p = e.getPoint();
            // if point is within arc show radial from frame center to arc
            if(ap.arc.contains(p))
                Rectangle2D r = ap.arc.getFrame();
                double dy = p.y - r.getCenterY();
                double dx = p.x - r.getCenterX();
                double theta = Math.atan2(dy, dx);
                double degrees = Math.toDegrees(theta);
                if(degrees < 0.0)
                    degrees += 360.0;
                if(containsAngle(degrees))
                    ap.setRadial(p, theta);           
         * Arc2D counts angles as increasing counter-clockwise
         * the Math class and the rest of the java.awt.geom
         *     package count angles as increasing clockwise
         * this method tries to bridge the difference
        private boolean containsAngle(double degrees)
            Arc2D arc = ap.arc;
            double start, extend, end;
            double extent = arc.getAngleExtent();
            if(extent > 0.0)
                start = -arc.getAngleExtent();
                end = start + arc.getAngleExtent();
                degrees -= 360.0;
            else
                start = arc.getAngleStart();
                end = start - arc.getAngleExtent();
            return start <= degrees && degrees <= end;
    }

  • Is a dilatation of a generalpath possible?

    Hi,
    I've got a generalpath that represents the inner contour of a floor plan. Interior like tables are also represented in this generalpath. It's the base for a little simulation program where persons should walk around. Now I'm looking for a way to create a dilatation (e.g. 25 pixel) of the objects and walls that i only need to simulate a single point moving around without paying attention to collide with door frames, tables, etc..
    Is there a way to do this? I hope my problem is understandable.
    Sincerely yours
    Andr�

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Dilatation extends JPanel {
        GeneralPath rooms;
        JLabel xLabel;
        JLabel yLabel;
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(rooms == null) initRooms();
            g2.setPaint(Color.blue);
            g2.draw(rooms);
            Rectangle r = rooms.getBounds();
            double x = r.getCenterX();
            double y = r.getCenterY();
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.scale(3.0, 3.0);
            at.translate(5, -30);
            g2.draw(at.createTransformedShape(rooms));
        private void initRooms() {
            rooms = new GeneralPath();
            rooms.moveTo(25,25);
            rooms.lineTo(125,25);
            rooms.lineTo(125,135);
            rooms.lineTo(25,135);
            rooms.lineTo(25,25);
            rooms.moveTo(75,25);
            rooms.lineTo(75,115);
            rooms.moveTo(75,125);
            rooms.lineTo(75,135);
            rooms.moveTo(40,50);
            rooms.lineTo(65,50);
            rooms.lineTo(65,85);
            rooms.lineTo(40,85);
            rooms.lineTo(40,50);
            rooms.moveTo(85,60);
            rooms.lineTo(110,60);
            rooms.lineTo(110,95);
            rooms.lineTo(85,95);
            rooms.lineTo(85,60);
        public static void main(String[] args) {
            Dilatation test = new Dilatation();
            test.addMouseMotionListener(test.pointer);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getLabel(), "Last");
            f.setSize(500,500);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        private JPanel getLabel() {
            xLabel = new JLabel();
            yLabel = new JLabel();
            Dimension d = new Dimension(45,25);
            JPanel panel = new JPanel(new GridBagLayout());
            panel.setBorder(BorderFactory.createEtchedBorder());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(1,1,1,1);
            addComponents(new JLabel("x ="), xLabel, panel, d, gbc, true);
            addComponents(new JLabel("y ="), yLabel, panel, d, gbc, false);
            return panel;
        private void addComponents(JComponent c1, JComponent c2, Container c,
                                   Dimension d, GridBagConstraints gbc, boolean b) {
            gbc.anchor = gbc.EAST;
            gbc.weightx = b ? 1.0 : 0;
            c.add(c1, gbc);
            c2.setPreferredSize(d);
            //c2.setBorder(BorderFactory.createEtchedBorder());
            gbc.anchor = gbc.WEST;
            gbc.weightx = b ? 0 : 1.0;
            c.add(c2, gbc);
        private MouseMotionListener pointer = new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                xLabel.setText(String.valueOf(e.getX()));
                yLabel.setText(String.valueOf(e.getY()));
    }

  • Graphics2D / Swing Density Issues

    Hi all,
    I'm relativley new to coding in java and first time posting in the forums so please be gentle.... I am writing a program that will work in unison w/ a graph drawing algorithm that was written in C. Java does the drawing and my C code does the calculations. The problem seems to be that my GUI when dealing with very large dense graphs starts to lag like crazy (long delay when buttons / menus are clicked). At first i thought it was constantly repainting the graph which would cause a lag but that does not seem to be the case. Can the graphics2d library just not handle something like a dense graph (like over 100,000 lines drawn to represent the edges)? Or have i fouled up my code. If you'd like, here is a link to it, it's not terribly complex (like i said, i'm new):
    http://www.rpi.edu/~boceke/Drawer.java
    Perhaps i'm going about drawing huge graphs in an inefficent way, like using a library i shouldn't be, and if that's the case please let me know what library i should be using to draw really dense graphs.
    Thanks much in advance,
    -Eli

    Just running this code, it takes about 1.5 - 2 seconds to draw 100,000 lines from random numbers. There's 2 versions, one which generates random numbers each time thru the loop, one that generates them before painting. Either case, the results are the same, so that tells me that painting that much is really slow.
    My only thought is that maybe somehow you can lessen what actually needs to be drawn. How you can do that, I don't know... I suppose it depends on the data.
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Draw extends JPanel {
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.getContentPane().add(new Draw());
              f.pack();
              f.setSize(500, 500);
              f.setVisible(true);
         private Random r = new Random();
         public void paintComponent(Graphics g) {
              System.out.println("start " + System.currentTimeMillis());
              g.setColor(Color.black);
              g.fillRect(0, 0, getSize().width, getSize().height);
              g.setColor(Color.yellow);
              int size = 100000;
              int x1, y1, x2, y2 = 0;
              for(int j = 0; j < size; j++) {
                   x1 = r.nextInt(400) + 50;
                   y1 = r.nextInt(400) + 50;
                   x2 = r.nextInt(400) + 50;
                   y2 = r.nextInt(400) + 50;
                   g.drawLine(x1, y1, x2, y2);
              System.out.println("end " + System.currentTimeMillis());
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Draw extends JPanel {
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.getContentPane().add(new Draw());
              f.pack();
              f.setSize(500, 500);
              f.setVisible(true);
         private static int size = 100000;
         private static int[] X1 = new int[size];
         private static int[] Y1 = new int[size];
         private static int[] X2 = new int[size];
         private static int[] Y2 = new int[size];
         private static Random r = new Random();
         static {
              for(int i = 0; i < size; i++) {
                   X1[i] = r.nextInt(400) + 50;
                   Y1[i] = r.nextInt(400) + 50;
                   X2[i] = r.nextInt(400) + 50;
                   Y2[i] = r.nextInt(400) + 50;
         public void paintComponent(Graphics g) {
              System.out.println("start " + System.currentTimeMillis());
              g.setColor(Color.black);
              g.fillRect(0, 0, getSize().width, getSize().height);
              g.setColor(Color.yellow);
              for(int j = 0; j < size; j++) {
                   g.drawLine(X1[j], Y1[j], X2[j], Y2[j]);
              System.out.println("end " + System.currentTimeMillis());
    }

  • Getting Error while decrypt a file using Blowfish algorithm

    I am using blowfish algorithm for encrypt and decrypt my file. this is my code for encrypting decrypting .
    while i am running program i am getting an Exception
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA12275)
    at Blowfishexe.main(Blowfishexe.java:65)
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.io.*;
    import org.bouncycastle.crypto.CryptoException;
    import org.bouncycastle.crypto.KeyGenerationParameters;
    import org.bouncycastle.crypto.engines.DESedeEngine;
    import org.bouncycastle.crypto.generators.DESedeKeyGenerator;
    import org.bouncycastle.crypto.modes.CBCBlockCipher;
    import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
    import org.bouncycastle.crypto.params.DESedeParameters;
    import org.bouncycastle.crypto.params.KeyParameter;
    import org.bouncycastle.util.encoders.Hex;
    public class Blowfishexe {
    public static void main(String[] args) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
              kgen.init(128);
              String keyfile="C:\\Encryption\\BlowfishKey.dat";
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
              System.out.println("key"+raw);
                   byte[] keyBytes = skey.getEncoded();
                   byte[] keyhex = Hex.encode(keyBytes);
                   BufferedOutputStream keystream =
    new BufferedOutputStream(new FileOutputStream(keyfile));
                        keystream.write(keyhex, 0, keyhex.length);
    keystream.flush();
    keystream.close();
    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
              System.out.println("secretKey"+skeySpec);
    FileOutputStream fos=new FileOutputStream("C:\\Encryption\\credit11.txt");
              BufferedReader br=new BufferedReader(new FileReader("C:\\Encryption\\credit.txt"));
              String text=null;
              byte[] plainText=null;
              byte[] cipherText=null;
              while((text=br.readLine())!=null)
              System.out.println(text);
              plainText = text.getBytes();
              cipherText = cipher.doFinal(plainText);
              fos.write(cipherText);
              br.close();
              fos.close();
              cipher.init(Cipher.DECRYPT_MODE, skeySpec);
              FileOutputStream fos1=new FileOutputStream("C:\\Encryption\\BlowfishOutput.txt");
              BufferedReader br1=new BufferedReader(new FileReader("C:\\Encryption\\credit11.txt"));
              String text1=null;
              /*while((text1=br1.readLine())!=null)
                   System.out.println("text is"+text1);
                   plainText=text1.getBytes("UTF8");
                   cipherText=cipher.doFinal(plainText);
                   fos1.write(cipherText);
              br1.close();
              fos1.close();
    //byte[] encrypted = cipher.doFinal("This is just an example".getBytes());
              //System.out.println("encrypted value"+encrypted);*/
    Any one pls tell me how to slove my problem
    thanks in advance

    hi
    i got the solution. its working now
    but blowfish key ranges from 56 to448
    while i am writing the code as
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(448);
    this code is generating the key upto 448 bits
    but coming to encoding or decode section key length is not accepting
    cipher.init(Cipher.ENCRYPT_MODE, key);
    Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at Blowfish1.main(Blowfish1.java:46)
    i am getting this error
    what is the solution for this type of exception.
    thank you

  • SHA2 Algorithm support in Adobe Acrobat 9

    Hello,
    1) Does Acrobat 9 supports SHA2 Hash algorithms while signing PDF file?
    2) As per my understanding PDF is signed using below approach
        Step 1. Take the PDF contents
        Step 2. Calculate the Hash of the content
        Step 3. Then sign(Encrypt) the hash. (here again we calculate the hash)
      So we are hashing the content twice.
      If I use SHA1 algorithm in Step2 and SHA2 algorithm in Step3, Adobe 9 is able to verify the signature. But if i use SHA2 algorithm in Step1 & Step 2
      Adobe 9 is saying "Content altered....."
      Why so?
    Please help.
    Thanks in advance
    Priyanka

    SHA2 was only added in Acrobat 9.1.  Also, the Microsoft Base CSP is needed for SHA2 support - Base CSP is included in Vista and Windows 7, but in XP it needs to be downloaded as a seperate addon.
    How are you setting the values in your SecurityHandler?  Off the top of my head, I believe in order to use SHA2 to hash the content (your "Step 2") you need to use AES-256 as your encryption algorithm which required a different cryptVersion be set in your SecurityHandler structure.

  • Application registration algorithm

    I'm writing a small shareware app that I would ideally like people to register. This is the classic, if they send in the registration code 'xxxxxx', then I can send the unlock code 'YYYYY' situation.
    Three criteria:
    1) I would like the registrtaion code xxxxx to be unique. I am toying with the idea of storing the date in millisecs of when the app was first run on the system. If anyone has any better suggestions, I would love to hear them.
    2) I would really like to have the algorithm myself. i.e. I don't plan to make enough off of this to be worth purchasing a library.
    3) This does not need to be incredibly secure. Just enough to keep the casual person from
    Does anyone out there have an algorithm they are willing to share to accomplish this?
    Thanks all. This falls into the 'I know it has to be a known problem, but I'm not sure where to start' category.

    Unless I am misunderstanding, I think that I'm addressing what you mentioned. Let me recap and see if I can make it more clear.
    1) Client sends you an identifier and saves it to the client's disk.
    String start = "" + System.currentTimeMillis();
    start = start.substring( start.length() - 5, start.length() );
    //this pulls off the last 6 numbers from the first run time and converts to a string. 
    // this is written to a file on the client side and then sent to me for registration.
    2) You (the server) send back a hash of the identifier.
    //registration app
    String start = codeSentFromCustomer;
    String superSecretDecoderString = "Secret Code";
    start = start + superSecretDecoderString;
    String result = MD5.getHashString( start );
    result = result.substring( result.length() - 9, result.length() );
    //this takes the 6 digits provided and appends "Secret Code".
    //  i.e. if the customer's code is "333232", then "333232Secret Code" is fed into MD5.
    //  I then send the customer the last 10 digits from my MD5 hash, say "1234567890" for simplicity sake
    3) Clients types the unlock code ("1234567890") into the registration box, which is then saved to disk.
    // to check on the unlock code's validity, I...
    String superSecretDecoderString = "Secret Code";
    String start = originalCodeFromAbove; //i.e. "333232" in this example
    start = start + superSecretDecoderString;  //now start = "333232Secret Code"
    String result2 = MD5.getHashString( start );
    result2 = result2.substring( result2.length() - 9, result2.length());
    // I compare the result2 to the stored unlock code to make sure they are equal
    //  superSecretDecoderString is stored within the client and the registration prog's code.  i.e.
    //  the customer never sees that string.
    4) At each startup the client code checks the hash of sent ID against the return he has stored.
    // run through the validation code detailed in #3.I think it addresses what you were referring to, but if it doesn't please tell me. It's my first crack at this sort of code, and I'd much rather discover any gaping holes now than later. :)
    thanks again

  • Fastest square root algorithm

    I was looking for a fast algorythm for integer square roots and I found this one http://medialab.freaknet.org/martin/src/sqrt/.
    The algorithm comes from a book by Mr C. Woo on how to do maths on an abacus.
    I post the javaized version here in case anyone finds it interesting.
    I believe this is the fastest square root function in existance for integers (and in game programming much of the time you aren't interested in fractions)
    /* Fast interger square root adapted from algorithm by Martin Guy @ UKC, June 1985.
        *   Origonally from a book on programming abaci by Mr C. Woo.
       public static int fastSqrt2(int n)
          int op, res, one;
          op = n;
          res = 0;
          /* "one" starts at the highest power of four <= than the argument. */
          one = 1 << 30;   /* second-to-top bit set */
          while (one > op) one >>= 2;
          while (one != 0)
             if (op >= res + one)
                op = op - (res + one);
                res = res +  (one<<1);
             res >>= 1;
             one >>= 2;
          return(res);
       }

    public static double sqrt(double a){
      if(a<0) throw new IllegalArgumentException("number<0");
      double precision=0.001;
      double x_nMinus1 = -1;
      double x_n = 1;
      while( Math.abs(x_n - x_nMinus1) > precision ) {
        x_nMinus1 = x_n;
        x_n = (x_nMinus1 * x_nMinus1 + a) / (2*x_nMinus1);          
      return x_n;           
    }

  • Square root algorithm?

    Okay, two things...I've always kinda wondered what the algorithm for the square-root function is...where would I find that?
    but the main thing is, I was making a class to store/deal with a complex/mixed number (a + b*i), and I was trying to make a square-root method for that. But I fiddled around with the variables in the equation, and I can't quite get any further.
    This is what I got (algebraically: this isn't actual code):
    ( the variables a, b, c, d are all real numbers )
    ( the constant i is the imaginary unit, sqrt(-1) )
    sqrt(a + b*i) == c + d*i
    a + b*i == (c + di)^2
    a + b*i == c*c - d*d + 2*c*d*i
    a == c*c - d*d
    b == 2*c*d
    c == sqrt( a + d*d )
    c == b / (2* d)
    d == sqrt( c*c - a )
    d == b / (2*c)
    right now the only thing i can conclude from that, is that if you know (a or b) and (c or d) you can determine the other variables. but I can't figure out how to define c or d purely in terms of a and b, as the method would need to. so I'm stuck.

    Okay, two things...I've always kinda wondered what the
    algorithm for the square-root function is...where
    would I find that?
    Math.sqrt()It's an extremely important skill to learn to read the API and become familiar with the tools you will use to program Java. Java has an extensive set of documentation that you can even download for your convenience. These "javadocs" are indexed and categorized so you can quickly look up any class or method. Take the time to consult this resource whenever you have a question - you'll find they typically contain very detailed descriptions and possibly some code examples.
    http://java.sun.com/reference/api/index.html
    http://java.sun.com/j2se/1.4.2/docs/api/

Maybe you are looking for