Awt.geom shape as Icon?

I want to use a geometric shape (specifically, a small circle) the icon for a JToggleButton. I can't use a static image as I need to be able to change the color of the icon. Is there any class that implements the Icon interface and has the methods of the awt.geom classes?
Thanks

Or like this?
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
public class ShapeIcon implements Icon {
    private final Paint paint;
    private final Shape shape;
    public ShapeIcon(Paint paint, Shape shape) {
        this.paint = paint;
        this.shape = shape;
    @Override
    public int getIconHeight() {
        return shape.getBounds().height;
    @Override
    public int getIconWidth() {
        return shape.getBounds().width;
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2 = ((Graphics2D) g);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(paint);
        g2.fill(AffineTransform.getTranslateInstance(x, y).createTransformedShape(shape));
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JLabel label = new JLabel(new ShapeIcon(
                        Color.RED, new Ellipse2D.Double(0, 0, 32, 32)));
                label.setBorder(BorderFactory.createLineBorder(Color.BLUE));
                JOptionPane.showMessageDialog(null, label);
}

Similar Messages

  • Bug in java.awt.geom.Rectangle2D.contains method

    I cannot understand why not awt.geom.Rectangle2D.contains() return the right value??? Or maybe i don�t understand it properly. Check out this code snippet
    import java.awt.geom.*;
    public class Test
        public static void main(String[] args)
           //Rectangle has a width of 2 and a height of 2 and starts drawing on cordinate 1,1
           Rectangle2D rect = new Rectangle2D.Double(1,1,2,2);      
           if (rect.contains(1,3))
               System.out.println("The cordinate is inside rectangle");
           else
               System.out.println("The cordinate is NOT NOT NOT inside rectangle");
    }The cordinate (1,3) is clearly contained in the rectangle or not?
    When you change the cordinate to (1,1) the method works correctly, so why diesn�t it work right with the cordinate (1,3). Can somebody please enlight me?
    Edited by: ripper079 on Dec 6, 2007 4:27 AM

    The cordinate (1,3) is clearly contained in the rectangle or not?Actually, it's a matter of opinion whether a point on the perimeter of a shape is considered contained in the shape or not. This is the implementation of java.awt.geom.Rectangle2D.contains (double x, double y)   public boolean contains(double x, double y) {
         double x0 = getX();
         double y0 = getY();
         return (x >= x0 &&
              y >= y0 &&
              x < x0 + getWidth() &&
              y < y0 + getHeight());
        }As can be seen from the code, the design team adopted a philosophy of returning false for coordinates that lie along the bottom and right sides of the Rectangle.
    If you require different behavior, you can always extend Rectangle2D.Double and override the methodimport java.awt.geom.Rectangle2D;
    public class Test extends Rectangle2D.Double {
        public Test (double x, double y, double w, double h) {
            super (x, y, w, h);
        public boolean contains (double x, double y) {
            double x0 = getX ();
            double y0 = getY ();
            return (x >= x0 &&
                    y >= y0 &&
                    x <= x0 + getWidth () &&
                    y <= y0 + getHeight ());
        public static void main (String[] args) {
            //Rectangle has a width of 2 and a height of 2 and starts drawing on cordinate 1,1
            Rectangle2D rect = new Test (1, 1, 2, 2);
            //Rectangle2D rect = new Rectangle2D.Double (1, 1, 2, 2);
            if (rect.contains (1,3))
                System.out.println ("The cordinate is inside rectangle");
            else
                System.out.println ("The cordinate is NOT inside rectangle");
    }db

  • Will 2D objects in java.awt.geom.* be Serializable in next version of Java?

    I am pretty frustrated about having to write my own Serializable classes. I'm not sure if this is the right place to ask, but will the next version of Java supports Serializable 2D objects?
    Further, I was trying to write my own class to extend java.awt.geom.GeneralPath to become Serializable, but it's declared "final". What should I do? (I had no problems with Rectangle2D.Double, Line2D.Double, etc.)
    Any help is greatly appreciated.
    Selwyn

    Your code for serializing the state of the General path forgets two things:
    1. the winding rule
    2. the segments types!
    You could use a vector, but I just directly wrote to the file:
    private void writeObject(ObjectOutputStream oos) throws IOException
    {     out.defaultWriteObject();
         //write state of transient GeneralPath _gp;
         out.writeInt(_gp.getWindingRule());
         float[] coord = new float[6];
         PathIterator i = _gp.getPathIterator(null);
         while(!i.isDone())
         {     int seg = i.currentSegment(coords);
              writeInt(seg);
              //switch on seg, writing correct # of floats from coords
              i.next();
         out.writeInt(-1);     //sentinel for end-of-data: SEG_LINETO etc are [0,4]
    private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException
    {     in.defaultReadObject();
         int rule = in.readInt();
         _gp = new GeneralPath(rule);
         //etc...
    }3. I'm just winging this code -- haven't tested it
    --Nax                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • AccessClassInPackage.sun.awt.geom

    My class imports sun.awt.geom.Crossings in order to implement a similar-to-java.awt.Polygon intersects method, upon float values. This takes place in an applet. The all known error message appears in the java console:
    java.security.AccessControlException: access denied (java.lang.RuntimePermission accessClassInPackage.sun.awt.geom)
    I should actually sign my applet just to import that package!? (lets say the policy file is not an option in my case)
    Why is that package different in such a way, than other packages? Is it not located together with all the other classes that compose the jre? (Also, is it documented somewhere?) May it be that the jre of the client that runs the applet would not necessarily provide this package or is it a standard in the J2SE jre?
    When an applet imports java.awt.Polygon (wihch imports sun.awt.geom.Crossings) no AccessControlException in thrown. I wonder.
    Thanks.
    mplexus2

    all the sun.* packages are offlimits to Applets since they contain code that could comprimise the system, and they do not contain any security checks. There may be an exception in one of the sun's get audio file.

  • Photoshop CS5 bug - shape layers icons disappear

    So I'm having this normal PSD when suddenly all the shape layer icons disappear and nothing seems to work to get them back. (I've tried restarting photoshop, computer, open the PSD from another PC) They work like they are there, double click and all that but just the icons are missing. It's not the first time happening and I noticed it happens after the layers get's a lot. Anyone has a fix for that?

    If you click on the fly-out menu icon at the upper-right of the Layers panel, then choose Panel Options, then choose a different sized icon, do they reappear?
    Only other thing that comes to mind is to update your display driver by visiting the web site of the manufacturer of your video card (e.g., nVidia.com or ATI.com) and locating the driver package that matches your hardware and operating system.
    Can you make a small PSD file (e.g., by cropping your master file quite a bit) and post it online?  Others could try opening it and seeing if the icons are there.
    -Noel

  • What use of having double precision in java.awt.geom?

    Hi,
    I am trying to draw a line using Line2D with this param:
    g2d.draw( new Line2D.Double( 1.1d, 1.5d, 1.9d, 1.5d ) );
    in my own JPanel paint method.
    However, the result is that the panel does not display a line nor a dot at all. Only when i change it to:
    g2d.draw( new Line2D.Double( 1.0d, 1.5d, 2.0d, 1.5d ) );
    that it draws a dot in the panel's first pixel.
    Can someone please guide or tell me why is this so? And what is the purpose of providing a double value for a geom ( such as Rentagle2D, Line2D, etc )?
    The actual case is that I have created a graph with x and y axis. I set the graph to be 400pixel * 400 pixels. And the scale for the graph is 1 million unit * 1 million unit which means a pixel would have contain (1000000/400) units, or 0.004 pixels represent 1 unit. The problem occurs when i try to draw a line that is only 10 unit.(which nothing is draw on the panel). I try to use all 2D geom with double precision, yet i could not get the result that I wanted. Isn't that java 2D will handle the double precision for graphing or drawing?
    Your help and reply is very much appreciated.
    Thank you.

    have in mind that you always have to fill 1 pixel to see anything as the panel has a 1 pixel grid.
    i guess the thing about double precision is in the contains(...) or crosses(...) methods of the geom.* objects.
    its nothing about drawing. how can you draw finer than the 1 pixel grid.
    even the antialias has to fill more pixel to make you thing the line is smooth. (BTW: antialias makes fonts widt less than 10px look terrible :))

  • Bug in java.awt.geom.Line2D?

    The method,
    public static double ptLineDistSq(double X1,
                                      double Y1,
                                      double X2,
                                      double Y2,
                                      double PX,
                                      double PY)calculates the squared distance between a line segment and a point.
    If however you pass in a line segment of zero length (X1=X2, Y1=Y2), the method performs a div by zero, which causes NaN to be returned.
    I believe this is a bug, as the method makes no exceptions to valid input, also mathmatically the distance from a point to a line segment still has a value even if the line segment has a zero length.
    A simple sanity check at the start of the method would fix it,
    if(X1==X2 && Y1==Y2) return (X1-PX)*(X1-PX)+(Y1-PY)*(Y1-PY);

    Yeah, im already working around it (i've actually just stolen their code, and switched it all from doubles to floats :D - it isn't a serious app. just a problem I encountered when answering a question in this Thread http://forum.java.sun.com/thread.jsp?forum=406&thread=420363&start=30&range=15&tstart=0&trange=15)
    I was realy just posting here for confirmation that it is a bug, before I reported it.

  • How to create a button on icon shape?

    i have a requirement that when i put the icon on button then the button will take the icon shape.
    i need to create buttons for icons shape. suppose i have star image icon so button will be of star shape, if icon is of triangle or arc shape then button will be of that shape exactly.
    how can i do that? any suggestions!!

    Check out the methods inherited from AbstractButton that pertain to whether the border is painted and whether the content area is filled.
    db

  • [Beginner] Moving a simple Shape

    Hi all !
    I need to write a simple application which draws basic shapes and let the user drag this shapes.
    I have found a sample code which does this with gif images rendered inside JLabels and adapted to use shapes (in this case a Ellipse2D) but nothing is drawn on the screen.
    Why ?
    Can anybody give me a help to fix it ?
    Thanks
    Francesco
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.Ellipse2D;
    import java.awt.image.BufferedImage;
    public class Main implements MouseMotionListener {
         JFrame frame;
         JLabel img;
         private final Graphics2D offscreen;
         public Main() {
              frame = new JFrame("test");
              frame.getContentPane().setLayout(null);
              frame.setBounds(0, 0, 500, 400);
              BufferedImage offscreenImage = new BufferedImage(200, 200,
                        BufferedImage.TYPE_INT_RGB);
              offscreen = offscreenImage.createGraphics();
              offscreen.setColor(Color.BLACK);
              offscreen.draw(new Ellipse2D.Double(10, 10, 120, 120));
              ImageIcon icon = new ImageIcon(offscreenImage);
              JLabel draw = new JLabel(icon);
              draw.addMouseMotionListener(this);
              frame.getContentPane().add(draw);
              frame.setVisible(true);
         public void mouseMoved(MouseEvent e) {
         public void mouseDragged(MouseEvent e) {
              img.setBounds(img.getX() + e.getX() - 10, img.getY() + e.getY() - 10,
                        36, 39);
         public static void main(String args[]) {
              new Main();
    }

    (1) When you use null layout you need to setBounds for each component, since there is no LayoutManager to take care of sizing and placement.
    (2) A newly constructed BufferedImage is filled with black pixels and drawing in black wouldn't show anyhow.
    Considering these two points, I've reworked your code... I renamed the reference variables as I find it inconvenient to have to remember that offscreen is in fact a Graphics2D object, and img is a JLabel. For future postings here, I strongly suggest that you name your variables after the class they represent... doing this will surely get you faster and better responses.import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Ellipse2D;
    import java.awt.image.BufferedImage;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class Main implements MouseMotionListener {
        JFrame frame;
        JLabel label;
        private final Graphics2D graphics2D;
        public Main () {
            frame = new JFrame ("test");
            frame.getContentPane ().setLayout (null);
            frame.setBounds (0, 0, 500, 400);
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            BufferedImage bufferedImage =
                    new BufferedImage (200, 200, BufferedImage.TYPE_INT_RGB);
            graphics2D = bufferedImage.createGraphics ();
            graphics2D.setColor (Color.RED); // changed
            graphics2D.draw (new Ellipse2D.Double (50, 50, 100, 100));
            ImageIcon imageIcon = new ImageIcon (bufferedImage);
            label = new JLabel (imageIcon);
            label.setBounds (0, 0, 104, 104); // added
            label.addMouseMotionListener (this);
            frame.getContentPane ().add (label);
            frame.setVisible (true);
        public void mouseMoved (MouseEvent e) { }
        public void mouseDragged (MouseEvent e) {
            label.setBounds (label.getX () + e.getX () - 10,
                    label.getY () + e.getY () - 10,
                    label.getWidth (), label.getHeight ());
        public static void main (String args[]) {
            new Main ();
    }You might want to use a MouseAdapter or add a MouseListener to capture the coordinates of mousePressed and use them as an offset for a more intuitive drag effect.
    Cheers, Darryl
    PS -- I'm not really into Graphics work, just trying to learn something new -- could you or somebody tell me why the Ellipse2D constructor doesn't seem to behave as per the documentation?
    public Ellipse2D.Double(double x, double y, double w, double h)
    Constructs and initializes an Ellipse2D from the specified coordinates.
    Parameters:
    x - the X coordinate of the upper-left corner of the framing rectangle
    y - the Y coordinate of the upper-left corner of the framing rectangle
    w - the width of the framing rectangle
    h - the height of the framing rectangle
    From this program, I found that x and y appear to be at the center, and not the upper-left corner, of the framing rectangle -- or is my understanding flawed?
    db

  • A better way to rotate a shape

    I need a way to easily rotate several Ellipse2D objects. The approach I'm using is not working because it's rotating the entire coordinate system in my Canvas object:
    public void paint(Graphics g) {     
    Graphics2D g2 = (Graphics2D) g;          
    Ellipse2D.Double e = new Ellipse2D.Double(220.0, 75.0, 47.0, 30.0);
    AffineTransform rotate45 =
    AffineTransform.getRotateInstance(Math.toRadians(161.5),
    220.0, 75.0);
    g2.setTransform(rotate45);
    g2.draw(e);
    } // end paint
    Is there something better to use other than AffineTransform that will allow me to rotate just the shape itself?
    thanks,
    Eric

    You can still use AffineTransform. There is a method called createTransformedShape and it does what you want.
    http://java.sun.com/j2se/1.4.1/docs/api/java/awt/geom/AffineTransform.html#createTransformedShape(java.awt.Shape)
    Ellipse2D e = ...
    AffineTransform rotate45 = ...
    e = (Ellipse2D) rotate45.createTransformedShape(e);
    ...

  • How do I join together arcs and lines in a single Shape???

    I am out of my depth, I am probably missing something spectacular .... I need to construct a shape from arcs and lines to get something like this, only closed:
    Like a winding river sort of thing... I do not need to draw this I need to have this shape and its area available to me.... How do I join these two arcs and two lines into a shape from which I can find - area.contains(xy.getX(), xy.getY()); , preatty please?
    here is the code that causes numerous errors:
    import java.awt.*;
    import java.awt.Graphics.*;
    import java.awt.Graphics2D.*;
    import java.awt.geom.RectangularShape.*;
    import java.awt.geom.Arc2D;
    import java.awt.geom.Line2D;
    import java.awt.geom.Rectangle2D;
    import java.awt.geom.Area;
    import java.awt.geom.GeneralPath;
    class MyShapes //extends Arc2D
    public static Arc2D outerOne;
    public static Arc2D innerOne;
    public static Line2D upLine, bottomLine;
    public static Area area = new Area();
    public MyShapes(double[] upper, double [] lower)
    outerOne.setArc(upper[0], upper[1], upper[2], upper[3], upper[4], upper[5], (int)upper[6]);
    //                         x,          y,               w,          h,               OA,      AA, int OPEN =1
    innerOne.setArc(lower[0], lower[1], lower[2], lower[3], lower[4], lower[5], (int)lower[6]);
    //outerTR=this.makeClosedShape(outerTopRightArc,middleTopRightArc);
    upLine     = new Line2D.Double(outerOne.getX(),outerOne.getY(),innerOne.getX(),innerOne.getY());
    bottomLine = new Line2D.Double(outerOne.getX()+outerOne.getWidth(),outerOne.getY()+outerOne.getHeight(),innerOne.getX()+innerOne.getWidth(),innerOne.getY()+innerOne.getHeight());
    area = this.joinAll(outerOne,innerOne, upLine, bottomLine);     
    private Area joinAll(Arc2D out, Arc2D in, Line2D one, Line2D two)
    GeneralPath joiner = new GeneralPath(out);
    joiner.append(in, true);
    joiner.append(one, true);
    joiner.append(two, true);      
    Area temp = new Area(joiner);
    return temp;     
    public boolean isInArea(Point xy)
    return area.contains(xy.getX(), xy.getY());     
    public boolean isItClosed()
    return area.isSingular();     
    Thanks

    Glad to hear you find what was wrong. Still, it doesn't the main problem : why is that method crashing?
    Here is what I've done in the mean time. See if it fits your purpose.import javax.swing.*;
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.geom.*;
    public class MyShapes {
         private Arc2D outerOne;
         private Arc2D innerOne;
         private Shape line1;
         private Shape line2;
         public MyShapes(double[] upper, double[] lower) {
              outerOne = new Arc2D.Double(upper[0],
                                                 upper[1],
                                                 upper[2],
                                                 upper[3],
                                                 upper[4],
                                                 upper[5],
                                                 0);
              innerOne = new Arc2D.Double(lower[0],
                                                 lower[1],
                                                 lower[2],
                                                 lower[3],
                                                 lower[4],
                                                 lower[5],
                                                 0);
              line1 = new Line2D.Double(outerOne.getStartPoint().getX(),
                                              outerOne.getStartPoint().getY(),
                                              innerOne.getStartPoint().getX(),
                                              innerOne.getStartPoint().getY());
              line2 = new Line2D.Double(outerOne.getEndPoint().getX(),
                                              outerOne.getEndPoint().getY(),
                                              innerOne.getEndPoint().getX(),
                                              innerOne.getEndPoint().getY());
         public void paint(Graphics2D aGraphics2D) {
              aGraphics2D.draw(outerOne);
              aGraphics2D.draw(innerOne);
              aGraphics2D.draw(line1);
              aGraphics2D.draw(line2);
         public static void main(String[] args) {
              double [] XO= {56, 58, 400, 280, 90, 90};// outter arc
              double [] XI={114, 105, 300, 200, 90, 90}; // inner arc
              final MyShapes myShapes = new MyShapes(XO, XI);
              JPanel panel = new JPanel() {
                   protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        Graphics2D g2 = (Graphics2D)g;
                        myShapes.paint(g2);
              final JFrame frame = new JFrame("Test shape");
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.setContentPane(panel);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.show();
    }

  • Problem in moving Rotated Shape object

    Hi All,
    I want to move the rotated shape object based on the mouse movement
    m able to move the object which is not rotated, but m facing the problem when i move the rotated object its moving position is not correct . I am expecting to maintain both shape objects movement is same, i mean if i did mouse movement to right rotated object moves upwards and normal object moves towards right insted of moving both r moving towards to right.
    Pls help me
    the following code is m using to moving the object
    The one which in red color is not rotated and the one which is in black color has rotated.
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import com.clinapps.LDPConstants;
    public class MoveRotatedObj extends JFrame
         public MoveRotatedObj()
              JPanel pane = new Dorairaj();
              add(pane);
         public static void main(String[] args)
              MoveRotatedObj f = new MoveRotatedObj();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(400, 400);
              f.setLocation(200, 200);
              f.setVisible(true);
         static class Dorairaj extends JPanel
              implements
                   MouseListener,
                   MouseMotionListener
              Shape o = null;
              Rectangle2D rect = new Rectangle2D.Double(
                   10, 10, 100, 100);
              Graphics2D g2 = null;
              boolean flag = true;
              int x=10,y=10,x1, y1, x2, y2;
              AffineTransform af = new AffineTransform();
              AffineTransform originalAt = new AffineTransform();
              int origin = 0;
              public Dorairaj()
                   addMouseListener(this);
                   addMouseMotionListener(this);
              protected void paintComponent(Graphics g)
                   super.paintComponent(g);
                   g2 = (Graphics2D) g;
                   g2.draw(new Rectangle2D.Double(0,0,500,500));
                   g2.translate(origin, origin);
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
                   rect = new Rectangle2D.Double(
                        x, y, 150, 100);
                   g2.setColor(Color.RED);
                   g2.draw(rect);
                   g2.setColor(Color.black);
                   originalAt = g2.getTransform();
                   g2.rotate(Math.toRadians(270), 200, 200);               
                   g2.draw(rect);
                   g2.setTransform(originalAt);
              * Invoked when a mouse button has been pressed on a component.
              public void mousePressed(MouseEvent e)
                   e.translatePoint(-origin, -origin);
                   x1 = e.getX();
                   y1 = e.getY();
              public void mouseDragged(MouseEvent e)
                   x2 = e.getX();
                   y2 = e.getY();
                   x = x + x2 - x1;
                   y = y + y2 - y1;
                   x1 = x2;
                   y1 = y2;
                   repaint();
              public void mouseMoved(MouseEvent e)
              * Invoked when the mouse button has been clicked (pressed and released)
              * on a component.
              public void mouseClicked(MouseEvent e)
                   repaint();
              * Invoked when a mouse button has been released on a component.
              public void mouseReleased(MouseEvent e)
              * Invoked when the mouse enters a component.
              public void mouseEntered(MouseEvent e)
              * Invoked when the mouse exits a component.
              public void mouseExited(MouseEvent e)
    Edited by: DoraiRaj on Sep 16, 2009 12:51 PM
    Edited by: DoraiRaj on Sep 16, 2009 1:00 PM
    Edited by: DoraiRaj on Sep 16, 2009 1:07 PM

    Thanks for replay and suggestion morgalr,
    I mean MoveRotatedObj1 is MoveRotatedObj only jsut m maintaing a copy on my system like MoveRotatedObj1.
    finally i solved my problem like this ,
    Is this correct approach m followinig or not pls let me know .
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import com.clinapps.LDPConstants;
    public class MoveRotatedObj extends JFrame
    public MoveRotatedObj()
      JPanel pane = new Dorairaj();
      add(pane);
    public static void main(String[] args)
      MoveRotatedObj f = new MoveRotatedObj();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setSize(400, 400);
      f.setLocation(200, 200);
      f.setVisible(true);
    static class Dorairaj extends JPanel
      implements
       MouseListener,
       MouseMotionListener
      Shape o = null;
      Rectangle2D rect = new Rectangle2D.Double(
       10, 10, 100, 100);
      Rectangle2D rect1 = new Rectangle2D.Double(
       10, 10, 100, 100);
      Graphics2D g2 = null;
      boolean flag = true;
      double lx, ly;
      int x = 10, y = 10, x1, y1, x2, y2;
      int l = 20, m = 20;
      int angle = 270;
      AffineTransform af = new AffineTransform();
      AffineTransform originalAt = new AffineTransform();
      int origin = 0;
      public Dorairaj()
       addMouseListener(this);
       addMouseMotionListener(this);
      protected void paintComponent(Graphics g)
       super.paintComponent(g);
       g2 = (Graphics2D) g;
       g2.draw(new Rectangle2D.Double(
        0, 0, 500, 500));
       g2.translate(origin, origin);
       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
       rect = new Rectangle2D.Double(
        x, y, 150, 100);
       g2.setColor(Color.RED);
       g2.draw(rect);
       rect1 = new Rectangle2D.Double(
        l, m, 150, 100);
       g2.setColor(Color.black);
       originalAt = g2.getTransform();
       g2.rotate(Math.toRadians(angle), 200, 200);
       g2.draw(rect1);
       g2.setTransform(originalAt);
      public void mousePressed(MouseEvent e)
       e.translatePoint(-origin, -origin);
       x1 = e.getX();
       y1 = e.getY();
      public void mouseDragged(MouseEvent e)
       boolean left, right, up, bottm;
       int dx, dy;
       left = right = up = bottm = false;
       x2 = e.getX();
       y2 = e.getY();
       dx = x2 - x1;
       dy = y2 - y1;
       x = x + dx;
       y = y + dy;
       up = dy < 0;
       bottm = dy > 0;
       left = dx < 0;
       right = dx > 0;
       if (left || right)
        // b += dx;
        m += dx;
       if (up || bottm)
        // a -= dy;
        l -= dy;
       x1 = x2;
       y1 = y2;
       repaint();
      public void mouseMoved(MouseEvent e)
      public void mouseClicked(MouseEvent e)
       repaint();
      public void mouseReleased(MouseEvent e)
      public void mouseEntered(MouseEvent e)
      public void mouseExited(MouseEvent e)
    }

  • Area.subtract( Shape ) doesn't work on Shape Line2D.Double?

    Hi all,
    I'm working on a method that will return a Shape from a BufferedImage that has transparent values, much like the one that dfgstg developed in [this thread|http://forums.sun.com/thread.jspa?messageID=9809317] . I'm having trouble understanding the difference between using this ( I'll call it line mode 1 ):Shape = Area.subtract( new Area( new Line2D().getBounds2D ) ) and this ( I'll call it line mode 2 ):Shape = Area.subtract( new Area( new Line2D().getBounds() ) ). When I use line mode 1, nothing gets subtracted when you use vertical or horizontal lines. When I use line mode 2, things show up, but I get the sense that it introduces artifacts into the resulting shape. Why is it necessary to turn a Line2D into a rectangle in order to subtract it from an Area? Line2D implements the Shape interface, so theoretically, it should be able to be subtracted from an Area. A program to demonstrate this problem ( between line mode 1 and line mode 2 ) is attached. Dfgstg uses line mode 2. Why is this necessary?
    // ShapeTest2.java
    // --- this code should compile ---
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    class ShapeTest2 extends JComponent
        public static final int LINE_MODE_1 = 1;
        public static final int LINE_MODE_2 = 2;
        Area _shape;   
        int _radius;
        int _diameter;
        Point2D.Double _center;
        ShapeTest2( int mode, int diameter )
            _diameter = diameter;
            _radius = _diameter/2;
            _center = new Point2D.Double( _diameter/2.0, _diameter/2.0 );
            setPreferredSize( new Dimension( _diameter, _diameter ) );
            _shape = new Area(
                new Ellipse2D.Double(
                    0, 0, _diameter, _diameter 
            switch( mode )
                case LINE_MODE_1:lineMode1();break;
                case LINE_MODE_2:lineMode2();break;
                default: break;                          
        private void lineMode1()
            Point2D p1 = new Point2D.Double();
            Point2D p2 = new Point2D.Double();
            double random1, random2, random3;
            boolean inside;
            // make and subtract fifty lines
            for ( int i = 0; i < 50; i++ )
                inside = false;
                // search random points until you find two that are
                // less than the radius' distance from the center
                while( inside == false )
                    random1 = Math.random()*_diameter;
                    random2 = Math.random()*_diameter;
                    random3 = Math.random()*_diameter;
                    // make sure they are horizontally related
                    // they have y in common
                    p1 = new Point2D.Double( random1, random2 );
                    p2 = new Point2D.Double( random3, random2 );
                    if ( ( p1.distance( _center ) < _radius )
                            && ( p2.distance( _center ) < _radius ) )
                        inside = true;
                _shape.subtract(
                    new Area(
                        // notice the getBounds2D - it returns a Rectangle2D
                        // it also doesn't show up for some reason
                        new Line2D.Double( p1, p2 ).getBounds2D()
        private void lineMode2()
            Point2D p1 = new Point2D.Double();
            Point2D p2 = new Point2D.Double();
            double random1, random2, random3;
            boolean inside;
            for ( int i = 0; i < 50; i++ )
                inside = false;
                while( inside == false )
                    random1 = Math.random()*_diameter;
                    random2 = Math.random()*_diameter;
                    random3 = Math.random()*_diameter;
                    // make sure they are horizontally related
                    p1 = new Point2D.Double( random1, random2 );
                    p2 = new Point2D.Double( random3, random2 );
                    if ( ( p1.distance( _center ) < _radius )
                            && ( p2.distance( _center ) < _radius ) )
                        inside = true;
                _shape.subtract(
                    new Area(
                        // getBounds() returns a rectangle
                        new Line2D.Double( p1, p2 ).getBounds()
        @Override
        protected void paintComponent( Graphics g )
            super.paintComponent( g );
            Graphics2D g2d = ( Graphics2D )g;
            g2d.setColor( Color.BLACK );
            g2d.draw( _shape );
        public static void main( String[] args )
            JFrame frame = new JFrame( "ShapeTest2" );
            int diameter = 300;
            ShapeTest2 lineMode1 =
                new ShapeTest2( ShapeTest2.LINE_MODE_1, diameter );
            ShapeTest2 lineMode2 =
                new ShapeTest2( ShapeTest2.LINE_MODE_2, diameter );
            frame.setLayout( new FlowLayout() );
            frame.add( lineMode1 );
            frame.add( lineMode2 );
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setLocation( 100, 100 );
            frame.pack();        
            frame.setVisible( true );
    }

    Keep all of your shapes right where they are! To make your text into hyperlinks then, just insert another shape...make it big or small enough to cover your text. Go ahead and drag it right over your text. Now attach the hyperlink to this shape. Now in the INspector,click over to the Graphics tab and change the opacity of this shape to 1%.
    You have now created a "hotspot" hyperlink over your text! All without moving any of your other shapes around! Publish and see the results... Let me know if it works out for you!

  • How to embed an Image onto a Shape?

    I'd like to use Shape.contains() and intersects() functionalities on clipped free-form Images on a custom component. Could we embed an Image into a Shape? If the answe is yes, then, how?
    If Shape is not usable, then, how could we achieve similar functionalities on Images? Do we only have run-of-the-mill coord caluculation?

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class ImageShapes extends JPanel {
        BufferedImage image;
        Shape[] shapes;
        JLabel xLabel, yLabel;
        ImageShapes(BufferedImage image) {
            this.image = image;
        public void setCoordinates(Point p) {
            String sx = "";
            String sy = "";
            if(p != null) {
                sx = String.valueOf(p.x);
                sy = String.valueOf(p.y);
            xLabel.setText(sx);
            yLabel.setText(sy);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(shapes == null)
                initShapes();
            Shape origClip = g2.getClip();
            for(int j = 0; j < shapes.length; j++) {
                g2.setClip(shapes[j]);
                Rectangle r = shapes[j].getBounds();
                // center image in clip shape
                int x = r.x + (r.width - image.getWidth())/2;
                int y = r.y + (r.height - image.getHeight())/2;
                g2.drawImage(image, x, y, this);
                // smooth the edges of the clipped image
                g2.setClip(null);  // or origClip
                g2.setPaint(getBackground());
                g2.draw(shapes[j]);
        private void initShapes() {
            int w = getWidth();
            int h = getHeight();
            shapes = new Shape[3];
            shapes[0] = new Ellipse2D.Double(w/2, h/3, 175, 175);
            int R = 60;
            int sides = 5;
            int[][]xy = generateShapeArrays(w/4, h/4, R, sides);
            shapes[1] = new Polygon(xy[0], xy[1], sides);
            GeneralPath path = new GeneralPath();
            double x1 = w/4;
            double y1 = h*9/16;
            double ctrlx1 = w*9/32;
            double ctrly1 = h*5/16;
            double ctrlx2 = w*11/16;
            double ctrly2 = h*9/16;
            double x2 = w/4;
            double y2 = h*15/16;
            CubicCurve2D curve = new CubicCurve2D.Double(x1, y1, ctrlx1, ctrly1,
                                                         ctrlx2, ctrly2, x2, y2);
            path.append(curve, false);
            AffineTransform at = AffineTransform.getTranslateInstance(w/2, 0);
            at.scale(-1,1);
            Shape left = at.createTransformedShape(curve);
            path.append(left, false);
            shapes[2] = path;
        private int[][] generateShapeArrays(int cx, int cy, int R, int sides) {
            int radInc = 0;
            if(sides % 2 == 0)
                radInc = 1;
            int[] x = new int[sides];
            int[] y = new int[sides];
            for(int i = 0; i < sides; i++) {
                x[i] = cx + (int)(R * Math.sin(radInc*Math.PI/sides));
                y[i] = cy - (int)(R * Math.cos(radInc*Math.PI/sides));
                radInc += 2;
            // keep base of triangle level
            if(sides == 3)
                y[2] = y[1];
            return new int[][] { x, y };
        private JPanel getLabels() {
            xLabel = new JLabel(" ");
            yLabel = new JLabel(" ");
            Dimension d = new Dimension(45, 25);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            addComponents(new JLabel("x"), xLabel, panel, gbc, d, false);
            addComponents(new JLabel("y"), yLabel, panel, gbc, d, true);
            panel.setBorder(BorderFactory.createEtchedBorder());
            return panel;
        private void addComponents(JComponent c1, JComponent c2, Container c,
                                   GridBagConstraints gbc, Dimension d, boolean b) {
            gbc.anchor = gbc.EAST;
            c.add(c1, gbc);
            c2.setPreferredSize(d);
            gbc.weightx = b ? 1.0 : 0;
            gbc.anchor = gbc.WEST;
            c.add(c2, gbc);
        public static void main(String[] args) throws IOException {
            BufferedImage image = ImageIO.read(new File("images/cougar.jpg"));
            ImageShapes test = new ImageShapes(image);
            test.addMouseMotionListener(new ShapeFinder(test));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getLabels(), "Last");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class ShapeFinder extends MouseMotionAdapter {
        ImageShapes imageShapes;
        boolean hovering = false;
        ShapeFinder(ImageShapes c) {
            imageShapes = c;
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            boolean haveSelection = false;
            Shape[] shapes = imageShapes.shapes;
            if(shapes == null) return;
            for(int j = 0; j < shapes.length; j++) {
                if(shapes[j].contains(p)) {
                    haveSelection = true;
                    imageShapes.setCoordinates(p);
                    if(!hovering)
                        hovering = true;
            if(!haveSelection && hovering) {
                hovering = false;
                imageShapes.setCoordinates(null);
    }

  • Create a object in form of circle, line, triangle or other shapes

    i am trying to make a program that creates simple objects, its just a hobby. the problem is i am trying to make an object that is only a line(for now). i mean i want to have an object that can be in a shape of anything in any angle. i like to be able to create a straight line from top left corner to bottom right corner, but i do not want to draw it, i want it to be an object like JButton but in different shapes. how ever i cannot do that. i have already wrote a little test program to show every one what i have, it s not my actual code just a sample.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JLayeredPane;
    import java.awt.BorderLayout;
    import javax.swing.JLabel;
    import java.awt.Color;
    import javax.swing.event.MouseInputListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JComponent;
    import javax.swing.AbstractButton;
    import java.awt.Graphics;
    import java.awt.Dimension;
    import java.awt.Polygon;
    import java.awt.Graphics2D;
    import java.awt.BasicStroke;
    import java.awt.RenderingHints;
    import java.awt.geom.Area;
    public class FractalTest extends JFrame
         public static final int H=600;
         public static final int W=600;
         public static final Dimension dim = new Dimension(H,W);
         private int[] joinInt = new int[]{BasicStroke.JOIN_MITER,BasicStroke.JOIN_ROUND,BasicStroke.JOIN_BEVEL};
         private int[] capInt = new int[]{BasicStroke.CAP_BUTT,BasicStroke.CAP_ROUND,BasicStroke.CAP_SQUARE};
         public FractalTest(){
              super("Test");
                    //two test lines
              Polygon p = new Polygon();
              p.addPoint(150,150);
              p.addPoint(450,450);
              Polygon s = new Polygon();
              s.addPoint(450,150);
              s.addPoint(150,450);
              setBackground(Color.YELLOW);
              setLayout(new BorderLayout());
                    //status bar at buttom
              JLabel info = new JLabel("info");
                    //creating JPanel holder of lines
              JPanelCanvas test = new JPanelCanvas();
              test.setBackground(Color.BLACK);
              test.setSize(dim);
              test.setLayout(new BorderLayout());
                    //creating lines
              TestComponent t1 = new TestComponent(p,2f,"Polygon P");
              TestComponent t2 = new TestComponent(s,5f,"Polygon S");
                    //setting JLables for status info
              t1.setInfoDisplay(info);
              t2.setInfoDisplay(info);
              test.setInfoDisplay(info);
              test.add(t1,BorderLayout.CENTER);
              test.add(t2,BorderLayout.CENTER);
              add(test,BorderLayout.CENTER);
              add(info,BorderLayout.SOUTH);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setSize(dim);
              setVisible(true);
              repaint();
         public static void main(String[] args){new FractalTest();}
         private class TestComponent extends AbstractButton implements MouseInputListener
              private float thickness;
              private Polygon polygon;
              private String name=null;
              private JLabel jl=null;
              public TestComponent(Polygon p,float t,String name){
                   super();
                   thickness=t;
                   polygon=p;
                   setContentAreaFilled(false);
                   this.name=name;
                   setSize(FractalTest.dim);
                   setVisible(true);
                   addMouseListener(this);
              public void paint(Graphics g){
                   super.paintComponent(g);
                   Graphics2D g2 = (Graphics2D)g;
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
                   g2.setStroke(new BasicStroke(thickness,capInt[0],joinInt[0]));
                   g2.setPaint(Color.GREEN);
                   g2.drawPolygon(polygon);
              public boolean contains(int x, int y){
                   int Ax=polygon.xpoints[0];
                   int Ay=polygon.ypoints[0];
                   int Bx=polygon.xpoints[1];
                   int By=polygon.ypoints[1];
                   int m=(By-Ay)/(Bx-Ax);
                   int s1=(m<=0)?+1:-1;
                   int s2=(m<=0)?-1:+1;
                   Polygon p = new Polygon();
                   p.addPoint(Ax+1,Ay+(int)(s1*thickness));
                   p.addPoint(Bx+1,By+(int)(s1*thickness));
                   p.addPoint(Bx-1,By+(int)(s2*thickness));
                   p.addPoint(Ax-1,Ay+(int)(s2*thickness));
                   return p.contains(x,y);
              public void setInfoDisplay(JLabel jl){this.jl=jl;}
              public void mouseEntered(MouseEvent e){jl.setText(name);}
              public void mouseExited(MouseEvent e){jl.setText("Polygon");}
              public void mouseDragged(MouseEvent e){}
              public void mouseMoved(MouseEvent e){}
              public void mouseClicked(MouseEvent e){}
              public void mousePressed(MouseEvent e){}
              public void mouseReleased(MouseEvent e){}
         private class JPanelCanvas extends JPanel implements MouseInputListener
              private JLabel jl;
              public JPanelCanvas(){}
              public void setInfoDisplay(JLabel jl){this.jl=jl;}
              public void mouseEntered(MouseEvent e){jl.setText("Canvas");}
              public void mouseExited(MouseEvent e){jl.setText("info");}
              public void mouseDragged(MouseEvent e){}
              public void mouseMoved(MouseEvent e){}
              public void mouseClicked(MouseEvent e){}
              public void mousePressed(MouseEvent e){}
              public void mouseReleased(MouseEvent e){}
    }if u see the code, the problem is each of the lines are covering the hole frame not just the green line, and i have to use the contains() method to limit the function but i do not want to do that. i just want it to be an object with out need of drawing any lines. just creating and object with the background color. so for example a JPanel in circular form that is only a circle no extra area around it.
    if u run the application and run it u will see the JPanel behind the green lines is not accessible by the mouse, the status JLabel shows the name of object can be reached by mouse at the moment and canvas(JPanel) will never be invoked. if the mouse is still on line objects the status name will stay on Polygon and it never changes to canvas.
    thanks everyone in advance

    Hi,
    try searching [www.java2s.com].plenty of sample programs are available.I have a faint memory of seeing a code that loads image files in desired placehoders like polygons n stuff. I guess you could replace the image component by some other component. Hope this helps

Maybe you are looking for

  • FAQ: How do I share my System Information?

    Many issues can be more easily tracked down if the engineers can examine your Photoshop System Info. Here's how to share it easily: Launch Photoshop Choose Help>System Info... Click the [Copy] button in the dialog and paste the info into any bug repo

  • OS X 10.9.4 Mavericks: Waking Up Unprompted While Sleeping

    I am running OS X 10.9.4 Mavericks on a 27-inch Mid 2011 iMac. Prior to upgrading to Mavericks, I would go to System Preferences_Energy Saver and set Display Sleep to 1 minute. This would keep the computer screen turned off at night, but would allow

  • Issue with being able to fill in data and save pdf forms in adobe reader

    Hi All, This is my first time posting on this forum so not sure what way to go about it so i'll just start by explaining my problem. I purchased adobe acrobat xi standard to create pdf forms(fillable forms) so that the receipents of these forms can o

  • My ipad 3 will not print to my canon 5320.

    the ipad sees the printer and gives me an activity line when i push "print". the canon 5320 just sits there - the screen does not change. thanks.

  • Scratch disk settings ignored

    Hi, I am using Photoshop CS5 Extended for Macintosh. (64bit) latest patch 12.0.4 I have a dedicated SSD drive and a RAIDed set of drives I am trying to use as my scratch disks. In the preferences I have these drives checked and have unchecked all  th