Solved

(URGENT!)How to draw multiple circles in java swing

Posted on 2006-11-22
8
701 Views
Last Modified: 2013-11-23
Hi there
Im doing a project, and i need to draw multiple circles that represent data; i get the coords and radius(as an arraylist)  from another program.

Im new and awful at java swing; and i need to write a method and constuctors to draw these circles, so i get the coords and radius from another program; i just dont know how to tell the java swing to draw all of them and i've been searching the sun website for days!

 Please may you post some demo code on how to draw circles in jswing to give me a nudge in the right direction??
Thanks in advance!
0
Comment
Question by:NadiaRashid
  • 5
  • 3
8 Comments
 
LVL 5

Expert Comment

by:sivachirravuri
ID: 18000725
Hi NadiaRashid.

Check the following link or code. Here is the example.

http://forum.java.sun.com/thread.jspa?threadID=782595


Code:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputAdapter;
 
public class CirclePanel extends JPanel
{
      private final Map shapesToLocations = new LinkedHashMap();
      private final Stroke stroke = new BasicStroke(3.0f);
      private final Paint paint = Color.BLACK;
 
      public static final void main(String[] args)
      {
            SwingUtilities.invokeLater(new Runnable()
            {
                  public void run()
                  {
                        CirclePanel p = new CirclePanel();
                        p.addShape(new Ellipse2D.Double(10.0, 10.0, 20.0, 20.0));
                        p.addShape(new Ellipse2D.Double(10.0, 40.0, 20.0, 20.0));
 
                        JFrame f = new JFrame();
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        f.setContentPane(p);
                        f.setSize(300, 300);
                        f.setLocationRelativeTo(null);
                        f.setVisible(true);
                  }
 
            });
      }
 
      public CirclePanel()
      {
            MouseHandler h = new MouseHandler();
            addMouseListener(h);
            addMouseMotionListener(h);
      }
 
      public void paintComponent(Graphics g)
      {
            super.paintComponent(g);
            
            Graphics2D g2d = ((Graphics2D) g);
            Paint p = g2d.getPaint();
            Stroke s = g2d.getStroke();
            g2d.setPaint(this.paint);
            g2d.setStroke(this.stroke);
            for (Iterator i = this.shapesToLocations.keySet().iterator(); i.hasNext();)
            {
                  Shape shape = (Shape) i.next();
                  Point location = (Point) this.shapesToLocations.get(shape);
                  g2d.translate(location.x, location.y);
                  g2d.draw(shape);
                  g2d.translate(- location.x, - location.y);
            }
            g2d.setPaint(p);
            g2d.setStroke(s);
      }
 
      public void addShape(Shape shape)
      {
            this.shapesToLocations.put(shape, new Point());
      }
 
      public void removeShape(Shape shape)
      {
            this.shapesToLocations.remove(shape);
      }
 
      private final class MouseHandler extends MouseInputAdapter
      {
            private Shape dragShape = null;
            private Point lastPoint = null;
 
            public void mousePressed(MouseEvent e)
            {
                  lastPoint = e.getPoint();
                  Point p = new Point();
                  for (Iterator i = shapesToLocations.keySet().iterator(); (this.dragShape == null) && i.hasNext();)
                  {
                        Shape shape = (Shape) i.next();
                        Point location = (Point) shapesToLocations.get(shape);
                        p.x = lastPoint.x - location.x;
                        p.y = lastPoint.y - location.y;
                        if (shape.contains(p))
                        {
                              this.dragShape = shape;
                        }
                  }
            }
            
            public void mouseReleased(MouseEvent e)
            {
                  this.dragShape = null;
                  this.lastPoint = null;
            }
 
            public void mouseDragged(MouseEvent e)
            {
                  if (this.dragShape != null)
                  {
                        Point location = (Point) shapesToLocations.get(this.dragShape);
                        location.x += (e.getX() - lastPoint.x);
                        location.y += (e.getY() - lastPoint.y);
                        this.lastPoint = e.getPoint();
                        repaint();
                  }
            }
      }
}

0
 

Author Comment

by:NadiaRashid
ID: 18000766
Hi sivachirravuri

Thanx for such a prompt response. This posting is a bit complicated, could you break it down for me? i just need to understand how i write a method to draw a circle...im confused because some online examples use elipses and others use a Circle method...i really have no idea whats going on with swing.

thanks for your response once again....nadia
0
 

Author Comment

by:NadiaRashid
ID: 18000790
correction, i mean fillOval NOT elipses...ooops :)
0
 
LVL 5

Accepted Solution

by:
sivachirravuri earned 500 total points
ID: 18001018
I'm only up to chapter four in this Lewis/Loftus book that has the exercise and I really have no intentions of looking into Swing since not much GUI usage is required for the cs class.

something like...

import java.awt.*;

public class Test
{
public Test()
{
}

public void drawCircle (Graphics circle, int xCenter, int yCenter, int radius, Color color)
{
circle.setColor (color);
circle.drawOval (xCenter-radius, yCenter-radius, 2*radius, 2*radius);
}
}

and then for a driver you just do something like...

import java.applet.Applet;
import java.awt.*;

public class Test1 extends Applet
{
public void paint (Graphics page)
{
Color bleh = Color.red;
Test blah = new Test();
Test.drawCircle( ????, 3 4, 6, bleh);
}
}

I know you said not to explicitly call paint (Graphics) but I was wondering if there was maybe a simpler yet possibly less practical way other than JPanel. As you can see, the ?'s show that my approach wasn't successful.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:NadiaRashid
ID: 18001029
thankx...i found a graphics one too...from sun.com

public void paint(Graphics g) {
        // Dynamically calculate size information
        // (the canvas may have been resized externally...)
         Dimension size = getSize();
         int d = Math.min(size.width, size.height); // diameter
         int x = (size.width - d)/4;
         int y = (size.height - d)/4;
     
        // draw circle (color already set to foreground)
         g.fillOval(x, y, d, d);
         g.setColor(Color.black);
         g.drawOval(x, y, d, d);
     
      }

except now it's hiding all the other stuff i have in my GUI so i need to find a JPanel method for drawing a circle...anyone got anything???
 
thanks for your input sivachirravuri
cheers
0
 
LVL 5

Expert Comment

by:sivachirravuri
ID: 18001037
Welcome. Did you find my second input understandable...? I hope it will be useful
0
 

Author Comment

by:NadiaRashid
ID: 18001042
0
 

Author Comment

by:NadiaRashid
ID: 18001104
second input is understandable...now for this post i just put up...just realised its using graphics tooo...but i sorta have direction on how to draw a circle....so you certainly did help...thank you!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
JAVA part two 5 41
unix in java example 9 42
Not needed 13 57
C# Error - Add Failed 12 49
A short article about a problem I had getting the GPS LocationListener working.
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now