Tooltiptext on a shape or a generalpath

Hi all,
is it possible to set a toolTipText when the mouse pointer stays over a Shape or a GeneralPath?
thanks

I tried to use getToolTipText as yuo explayned but maybe I didnt understand very weel...
When exactly I have to invoce that method?
Is setTooltipText method necessary?
Maybe a simple example could be useful...
thanks

Similar Messages

  • ToolTipText on JFrames

    Hi,
    is there a possibilty of implementing ToolTipText feature directly onto a JFrame ... I am having a JFrame with several shape objects being drawn without having any JPanels involved ... and I want to implement ToolTipText on these Shape objects ... is there a way to do it .. or do we necessarily have to use JPanels ?

    Hi
    It looks like you have to at least put a JPanel onto the JFrame in order to use a tooltip. I figured that out using Netbeans. Its really nice for making GUI's. It's got a window with all of the properties of whatever Swing or AWT component you need to use (tooltip, name, size, etc). I highly recommend it. Hope this helps.
    Regards,
    Jay

  • Rotating with Mouse using 2D

    Hello,
    I have a shape created using GeneralPath and have hot-points once the user selects the Shape.I would like to add a feature which allows user to rotate the shape using/clicking&dragging the MOUSE.Can anyone please tell me how can I derive the angle between the shape center and mouse dragged position?Any sample code doing this.???
    thanks

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Rotation {
      public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new RotationPanel(200,100,100));
        f.setSize(400,300);
        f.setLocation(300,400);
        f.setVisible(true);
    class RotationPanel extends JPanel {
      int cx, cy, size;
      double radians;
      Shape polygon;
      Area area, tabArea;
      int deltaX, deltaY;
      int shapeIndex = -1;
      boolean
        okToRotate = false,
        showTab = false;
      public RotationPanel(int cx, int cy, int size) {
        this.cx = cx;
        this.cy = cy;
        this.size = size;
        radians = 0;
        setBackground(Color.white);
        addMouseListener(new SelectionListener());
        addMouseMotionListener(new RotateListener());
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        int R = (int)(size / (4 * Math.cos(Math.PI/5) * Math.sin(Math.PI/5)));
        int[] x = new int[5];
        int[] y = new int[5];
        for(int i = 0; i < 5; i++) {
          x[i] = cx + (int)(R * Math.sin(radians*Math.PI/5));
          y[i] = cy - (int)(R * Math.cos(radians*Math.PI/5));
          radians += 2;
        polygon = new Polygon(x, y, 5);
        area = new Area((Shape)polygon);
        g2.setPaint(Color.blue);
        g2.draw(polygon);
        if(showTab) {
          int xR = cx + (int)(1.4 * R * Math.sin(radians*Math.PI/5));
          int yR = cy - (int)(1.4 * R * Math.cos(radians*Math.PI/5));
          //g2.draw(new Line2D.Double(cx, cy, xR, yR));
          int r = (int)(R * Math.cos(Math.PI/5));
          int xr = cx + (int)(1.4 * r * Math.sin((radians + 1)*Math.PI/5));
          int yr = cy - (int)(1.4 * r * Math.cos((radians + 1)*Math.PI/5));
          //g2.draw(new Line2D.Double(cx, cy, xr, yr));
          int[] xTab = new int[4];
          int[] yTab = new int[4];
          xTab[0] = x[0];
          xTab[1] = xR;
          xTab[2] = xr;
          xTab[3] = cx + (int)(r * Math.sin((radians + 1)*Math.PI/5));
          yTab[0] = y[0];
          yTab[1] = yR;
          yTab[2] = yr;
          yTab[3] = cy - (int)(r * Math.cos((radians + 1)*Math.PI/5));
          Polygon tabPolygon = new Polygon(xTab, yTab, 4);
          tabArea = new Area(tabPolygon);
          g2.setPaint(Color.red);
          g2.fill(tabPolygon);
      class SelectionListener extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
          int x = e.getX();
          int y = e.getY();
          if(area.contains(x,y)) {
            deltaX = (cx - x);
            deltaY = (cy - y);
            shapeIndex = 1;
          if(showTab && tabArea.contains(x,y))
            okToRotate = true;
          else
            okToRotate = false;
        public void mouseReleased(MouseEvent e) {
          shapeIndex = -1;
          okToRotate = false;
        public void mouseClicked(MouseEvent e) {
          if(area.contains(e.getX(), e.getY()))
            showTab = true;
          else
            showTab = false;
          repaint();
      class RotateListener extends MouseMotionAdapter {
        public void mouseDragged(MouseEvent e) {
          int x = e.getX();
          int y = e.getY();
          if(shapeIndex > 0) {
            cx = x + deltaX;
            cy = y + deltaY;
          if(okToRotate) {
            int px = cx - x;
            int py = cy - y;
            int phi = (int)(Math.acos(py/Math.sqrt(px*px + py*py))*180);
            if(x < cx)
              phi *= -1;
            radians = phi * Math.PI/180;     
          repaint();
    }

  • If you know C#

    Hi,
    Sorry to be a pain, just wondered if someone could help me please. Could someone please convert this C# code to java please?
    private Region GetRegion(Bitmap _img, Color color)
                Color _matchColor = Color.FromArgb(color.R, color.G, color.B);
                System.Drawing.Region rgn = new Region();
                rgn.MakeEmpty();
                Rectangle rc = new Rectangle(0, 0, 0, 0);
                bool inimage = false;
                for (int y = 0; y < _img.Height; y++)
                    for (int x = 0; x < _img.Width; x++)
                        if (!inimage)
                            if (_img.GetPixel(x, y) != _matchColor)
                                inimage = true;
                                rc.X = x;
                                rc.Y = y;
                                rc.Height = 1;
                        else
                            if (_img.GetPixel(x, y) == _matchColor)
                                inimage = false;
                                rc.Width = x - rc.X;
                                rgn.Union(rc);
                    if (inimage)
                        inimage = false;
                        rc.Width = _img.Width - rc.X;
                        rgn.Union(rc);
                return rgn;
            }I need to add it some where in here.
    public void paintComponent( Graphics g ) {
    Graphics2D g2d= (Graphics2D)g;
    g2d.setColor( new Color( 255, 0, 0 ) );
    g2d.draw( a );
    } // end paintComponentThanks
    Bob

    My code does not compile what have I done wrong
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class TestShape {
    private static class DisplayComponent extends JComponent {
    private Shape s;
    private GeneralPath p = new GeneralPath();
    private Area a;
    public DisplayComponent() {
    this.setSize( 500, 500 );
    this.setPreferredSize( new Dimension( 500, 500 ) );
    p.append( new Ellipse2D.Double( 50, 50, 50, 50 ), false );
    p.append( new Ellipse2D.Double( 75, 75, 50, 50 ), false );
    p.append( new Ellipse2D.Double( 150, 150, 50, 50 ), false );
    a = new Area( p );
    } // end DisplayComponent
    public void paintComponent( Graphics g ) {
    Graphics2D g2d= (Graphics2D)g;
    g2d.setColor( new Color( 255, 0, 0 ) );
    g2d.draw( a );
    } // end paintComponent
    } // end clas
    private Region GetRegion(Bitmap _img, Color color)
                Color _matchColor = Color.FromArgb(color.R, color.G, color.B);
                Stuff.Drawing.Region rgn = new Region();
                rgn.MakeEmpty();
                Rectangle rc = new Rectangle(0, 0, 0, 0);
                boolean inimage = false;
                for (int y = 0; y < _img.Height; y++)
                    for (int x = 0; x < _img.Width; x++)
                        if (!inimage)
                            if (_img.GetPixel(x, y) != _matchColor)
                                inimage = true;
                                rc.X = x;
                                rc.Y = y;
                                rc.Height = 1;
                        else
                            if (_img.GetPixel(x, y) == _matchColor)
                                inimage = false;
                                rc.Width = x - rc.X;
                                rgn.Union(rc);
                    if (inimage)
                        inimage = false;
                        rc.Width = _img.Width - rc.X;
                        rgn.Union(rc);
                return rgn;
    public static void main( String[] args ) {
    JFrame frame = new JFrame();
    DisplayComponent c = new DisplayComponent();
    frame.getContentPane().add( c );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible(true);
    } // end main
    } // end class TestShapeThanks
    Loftty

  • Customized axis value in JFreeChart

    I am using JFreeChart 0.921
    I have a set of data, for example
    x - 0.0, 0.4, 1.3, 1.9, 2.3, 3.3 and
    y - 0.0, 1.0, 2.0, 3.0, 4.0, 5.0.
    I can make XYPlot, and x-axis scale shows 0 to 4. What I want is to display the scales using the numbers of x, as
    0.0 0.4 1.3 1.9 2.3 3.3,
    not
    0.0 1.0 2.0 3.0 4.0.
    Can JFreeChart do this and how? Any examples? Thanks.

    Then how do I implement into my code
    public class Audiogram extends JApplet{
         //CategoryDataset dataset;
         JFreeChart chart;
         ChartPanel chartPanel;
       public void init(){
            XYSeries seriesAC_Rt = new XYSeries("AC Rt");
            seriesAC_Rt.add(0.25, 25.0);
            seriesAC_Rt.add(0.50, 25.0);
            seriesAC_Rt.add(1.00, 15.0);
            seriesAC_Rt.add(2.00, 10.0);
            seriesAC_Rt.add(3.00, 5.0);
            seriesAC_Rt.add(4.00, 10.0);
            seriesAC_Rt.add(6.00, 5.0);
            seriesAC_Rt.add(8.00, 5.0);
             XYSeries seriesAC_M_Lt = new XYSeries("AC (masked)");
            seriesAC_M_Lt.add(0.25, 80.0);
            seriesAC_M_Lt.add(0.50, 90.0);
            seriesAC_M_Lt.add(1.00, 85.0);
            seriesAC_M_Lt.add(2.00, 75.0);
            seriesAC_M_Lt.add(3.00, 55.0);
            seriesAC_M_Lt.add(4.00, 70.0);
            seriesAC_M_Lt.add(6.00, 65.0);
            seriesAC_M_Lt.add(8.00, 55.0);
             XYSeries seriesAC_Lt = new XYSeries("AC Lt");
            seriesAC_Lt.add(0.25, 75.0);
            seriesAC_Lt.add(0.50, 75.0);
            seriesAC_Lt.add(1.00, 75.0);
            seriesAC_Lt.add(2.00, 70.0);
            seriesAC_Lt.add(3.00, 50.0);
            seriesAC_Lt.add(4.00, 65.0);
            seriesAC_Lt.add(6.00, 60.0);
            seriesAC_Lt.add(8.00, 50.0);
            XYSeries seriesBC_M_Lt1 = new XYSeries("BC (masked)");
            seriesBC_M_Lt1.add(0.50, 60.0);
            seriesBC_M_Lt1.add(1.00, 65.0);
            XYSeries seriesBC_M_Lt2 = new XYSeries("BC (masked)");
            seriesBC_M_Lt2.add(1.80, 70.0);
            XYSeries seriesBC_M_Lt3 = new XYSeries("BC (masked)");
            seriesBC_M_Lt3.add(2.80, 50.0);
            XYSeries seriesBC_M_Lt4 = new XYSeries("BC (masked)");
            seriesBC_M_Lt4.add(3.50, 60.0);
            XYSeriesCollection dataset= new XYSeriesCollection();
            dataset.addSeries(seriesAC_Rt);
            dataset.addSeries(seriesAC_Lt);
            dataset.addSeries(seriesAC_M_Lt);
            dataset.addSeries(seriesBC_M_Lt1);
            dataset.addSeries(seriesBC_M_Lt2);
            dataset.addSeries(seriesBC_M_Lt3);
            dataset.addSeries(seriesBC_M_Lt4);
            XYDataset ds = (XYDataset)dataset;
            // create a chart...
            JFreeChart chart = ChartFactory.createXYLineChart(
                "Puretone Audiogram",
                "Hearing Level in dB",   
                "Frequency in Khz",   
                ds,
                PlotOrientation.VERTICAL,
                false,
                   true,
                   false
           XYPlot plot = (XYPlot)chart.getXYPlot();
            // customise the range axis...
            plot.setDomainGridlinesVisible(true);
            plot.setDomainGridlinePaint(Color.BLUE);
            plot.setRangeGridlinesVisible(true);
            plot.setRangeGridlinePaint(Color.BLUE);
            plot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
            plot.getRangeAxis().setInverted(true);
            // customise the y-axis...
            NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
            rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
            rangeAxis.setTickUnit(new NumberTickUnit(10.0));
            rangeAxis.setAutoRangeIncludesZero(true);
            rangeAxis.setUpperBound(110.0);
            rangeAxis.setLowerBound(-10.0);
            // customise the x axis...
            NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
            domainAxis.setAutoRangeIncludesZero(true);
            domainAxis.setUpperBound(8.0);
        /*    TickUnits standardUnits = new TickUnits();
            standardUnits.add(new NumberTickUnit(0.25));
            standardUnits.add(new NumberTickUnit(0.5));
            standardUnits.add(new NumberTickUnit(1));
            standardUnits.add(new NumberTickUnit(2));
            standardUnits.add(new NumberTickUnit(3));
            standardUnits.add(new NumberTickUnit(4));
            standardUnits.add(new NumberTickUnit(6));
            standardUnits.add(new NumberTickUnit(8));
            domainAxis.setStandardTickUnits(standardUnits);
            // display legends on graph
            //StandardLegend legend = (StandardLegend) chart.getLegend();
            //legend.setDisplaySeriesShapes(true);
            //chart.getLegend().setAnchor(Legend.EAST);
            plot.getRenderer().setSeriesPaint(3, Color.MAGENTA);
            plot.getRenderer().setSeriesPaint(4, Color.MAGENTA);
            plot.getRenderer().setSeriesPaint(5, Color.MAGENTA);
            plot.getRenderer().setSeriesPaint(6, Color.MAGENTA);
            StandardXYItemRenderer renderer = (StandardXYItemRenderer) plot.getRenderer();
            renderer.setPlotShapes(true);
            renderer.setShapesFilled(false);
            Shape[] shapes = new Shape[7];
            int[] xpoints;
            int[] ypoints;
            // legend shape circle
            shapes[0] = new Ellipse2D.Double(-5, -5, 10, 10);
            // legend shape x
            GeneralPath x = new GeneralPath();
            x.moveTo(-5f, -5f);
            x.lineTo(5f, 5f);
            x.moveTo(5f, -5f);
            x.lineTo(-5f, 5f);
            shapes[1] = (Shape)x;
            // legend shape triangle
            //xpoints = new int[] {-5, 0, 5};
            //ypoints = new int[] {5, -5, 5};
            //shapes[2] = new Polygon(xpoints, ypoints, 3);
            // legend shape square
            shapes[2] = new Rectangle2D.Double(-5, -5, 10, 10);
            // legend shape right angle
            //GeneralPath la = new GeneralPath();
            //la.moveTo(5f, 1f);
            //la.lineTo(-5f, 5f);
            //la.moveTo(5f, 1f);
            //la.lineTo(-5f, -5f);
            //shapes[2] = (Shape)la;
            // legend shape left angle
            //GeneralPath la = new GeneralPath();
            //la.moveTo(-5f, 1f);
            //la.lineTo(5f, -5f);
            //la.moveTo(-5f, 1f);
            //la.lineTo(5f, 5f);
            //shapes[2] = (Shape)la;
            // legend shape left bracket
            //GeneralPath lb = new GeneralPath();
            //lb.moveTo(3f, -5f);
            //lb.lineTo(-3f, -4f);
            //lb.lineTo(-3f, 4f);
            //lb.lineTo(3f, 5f);
            //shapes[2] = (Shape)lb;
            // legend shape right bracket
            //GeneralPath rb = new GeneralPath();
            //rb.moveTo(-3f, 5f);
            //rb.lineTo(3f, 4f);
            //rb.lineTo(3f, -4f);
            //rb.lineTo(-3f, -5f);
            //shapes[3] = (Shape)rb;
            // legend shape circle arrow right
            Shape tempCircle = new Ellipse2D.Double(-3, -5, 10, 10);
            xpoints = new int[] {-5, 4, -6};
            ypoints = new int[] {14, 9, 6};
            Shape tempTra = new Polygon(xpoints, ypoints, 3);
            GeneralPath car = new GeneralPath();
            car.moveTo(-5f, -5f);
            car.append(tempCircle, false);
            car.moveTo(2f, 4f);
            car.lineTo(-1f, 8f);
            car.append(tempTra, false);
            car.closePath();
            shapes[3] = (Shape)car;
            shapes[4] = (Shape)car;
            shapes[5] = (Shape)car;
            shapes[6] = (Shape)car;
            // legend shape circle arrow left
      /*      Shape tempCircle = new Ellipse2D.Double(-3, -5, 10, 10);
            xpoints = new int[] {1, 12, 10};
            ypoints = new int[] {10, 6, 15};
            Shape tempTra = new Polygon(xpoints, ypoints, 3);
            GeneralPath car = new GeneralPath();
            car.moveTo(-5f, -5f);
            car.append(tempCircle, false);
            car.moveTo(2f, 4f);
            car.lineTo(8f, 8f);
            car.append(tempTra, false);
            shapes[3] = (Shape)car;
            DrawingSupplier supplier = new DefaultDrawingSupplier(
                DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                shapes
            plot.setDrawingSupplier(supplier);
            plot.getRenderer().setSeriesStroke(3, new BasicStroke(2.0f,
                    BasicStroke.CAP_ROUND,
                    BasicStroke.JOIN_BEVEL,
                    1.0f,
                    new float[] {2.0f, 6.0f},
                    0.0f));
             // display chart on panel
             chartPanel = new ChartPanel(chart);
             chartPanel.setPreferredSize(new Dimension(500, 500));
             JLabel image = new JLabel(new ImageIcon("legend.gif"));
              Container c = getContentPane();
              c.setLayout(new BorderLayout());
              c.add(chartPanel, BorderLayout.CENTER);
              c.add(image, BorderLayout.EAST);

  • 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();
    }

  • 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);
    }

  • Alternative to GeneralPath?

    I'm looking for an alternative to GeneralPath that supports double precision.
    Specifically I want to create an Area in double precision. Any suggestions?
    Thx,
    Mark

    You won't find it in the standard API. You can write your own class by extending Shape. If the methods in GeneralPath suit you then you can just take the source code and modify it so that the points are stored in double precision.

  • Why no Polygon2d? Is GeneralPath the alternative?

    In Java2D all the old shapes got new Shape versions with
    double precision - except for Polygon.
    Id like to have a Polygon that uses double precision.
    Im thinking that maybe they didnt update Polygon because
    GeneralPath should be its replacement in Java2D (it has
    float precision)?
    For graphics intensive operations - is one "faster" than the other?
    Thanks!

    this probably does not help you much, but, as the writer of a 225+ FPS game engine, I am proud to say that GeneralPaths seem to not hinder rendering at all (as every shape in my engine is stored as one). I do not think there is much of a loss at all when rendering a GeneralPath as opposed to a Polygon because (correct me if I'm wrong) the data is still stored in sequential order, so that in essence the drawing process does the same thing, just through a different object...
    Hope that helps your last question a little
    Alex

  • Set a tooltip for a shape, not a button

    Hi everybody,
    Hope you are all ok wherever you are :)
    I have this little problem guys; I want to set a tooltip button in my application but the problem is that i'm not using buttons but shapes instead, in which shapes i've added mouse click handle code.
    I need when the mouse goes over these shapes-buttons i have, some tooltip text to be displayed. I've tried to create a rectangle and display the small text i want into that rectangle and then call repaint for restoring the program to the previous state before the tooltip display, but unfortunately it is too slow.
    Can you please help me out of that? Can you give a way of setting tooltips for shapes instead of buttons?
    Any help would be appreciated.
    Thanks,
    -John

    Your trying to set a tooltip for a given area on some JComponent defined by a Shape which holds the points that make up the border of the Shape, like GeneralPath or something like that? Is that what you mean? I'm not sure but I think you can use Shape.contains(Point2D ...) without actually have drawn the Shape, so that you can test where the mouse is on your JComponent, then check contains to see if a tooltip needs to be displayed. You'll have to write your own tooltip frame that's not dependent on a JComponent, but thats fairly straightforward. Don't know if this is any help to you, but its a possibility.
    Tom
    ioannisc: the OP talks about the use of Shape's, where did subclasses of JComponent come into it?!

  • Is there a method for actually rotating the co-ordinates of 2D shapes?

    Hallo
    I'm trying to create a Graphics2D-powered program that needs to include polygons that can rotate. Now, as far as I can tell, affinetransform's methods will only ever transform the co-ordinate system of the User Space. So, for example, a GeneralPath object's co-ordinates will not change at all. Its useful only for rotating the Graphics2D display, not the underlying object.
    But I want to actually transform the co-ordinates of the Shape - e.g. select a rotation point (the centroid) of a Shape, and get a new set of co-ordinates for its points that rotates it by x radians. This is because I'm not using it just for display - it will be used to check what points are inside it, and needs to stick to the sprite it's used by.
    Is there any way of doing this - using a Shape object persistently, and just moving it and rotating it? Or do I need to make a new one every time, with new co-ordinates? Will I need to write my own rotate function? (Doable, just basic trig, but I kinda hoped there'd be a method somewhere...!)
    Cheers...

    sorry, the 'would you mind' wasn't meant to sound
    snotty! its amazing how bad forums can be for getting
    feeling across. I meant to say something like 'oh
    hell, I can't see how to do this. I don't suppose you
    happen to have an example lying around the place, do
    you?'
    I'll give it a go...I sounded a bit harsh perhaps. Sorry.
    I only saw someone give an answer and a couple of minutes later a follow-up asking for "example code", which lead me to believe you did not do any research/googling on what was suggested. I now read your original post and saw that you already knew of the AffineTransform class.
    Anyway, when I want to see some classes "in action" I always go to http://www.exampledepot.com . It also has some snippets on how to use the AffineTransform class:
    http://www.google.com/custom?domains=exampledepot.com&q=AffineTransform&sa=Google+Search&sitesearch=exampledepot.com&client=pub-6001183370374757&forid=1&ie=ISO-8859-1&oe=ISO-8859-1&cof=GALT%3A%23008000%3BGL%3A1%3BDIV%3A%23336699%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3A336699%3BALC%3A0000FF%3BLC%3A0000FF%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BFORID%3A1%3B&hl=en
    Good luck.

  • Drawing an arrow between two rectangle shapes

    i am trying to draw an arrow between two rectangle shapes. the arrow will start from the center of one rectangle and end with the arrow tip at the edge of the other rectangle. i actually draw the arrow first, and draw the rectangles last so the effect of where the arrow starts will seem to come from the edge and not the center.
    i have code using some trigonmetry that works for squares, but as soon as the shape becomes a rectangle (i.e. width and height are not the same), the drawing breaks.
    can i detect where a line intersects with a shape through clipping and use that point location to draw my arrow head? if so, how?

    Here's one way to do this using the rule of similar triangles.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Pointers extends JPanel {
        Rectangle r1 = new Rectangle(40,60,100,150);
        Rectangle r2 = new Rectangle(200,250,175,100);
        int barb = 20;
        double phi = Math.toRadians(20);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.blue);
            g2.draw(r1);
            g2.draw(r2);
            g2.setPaint(Color.red);
            g2.draw(getPath());
        private GeneralPath getPath() {
            double x1 = r1.getCenterX();
            double y1 = r1.getCenterY();
            double x2 = r2.getCenterX();
            double y2 = r2.getCenterY();
            double theta = Math.atan2(y2 - y1, x2 - x1);
            Point2D.Double p1 = getPoint(theta, r1);
            Point2D.Double p2 = getPoint(theta+Math.PI, r2);
            GeneralPath path = new GeneralPath(new Line2D.Float(p1, p2));
            // Add an arrow head at p2.
            double x = p2.x + barb*Math.cos(theta+Math.PI-phi);
            double y = p2.y + barb*Math.sin(theta+Math.PI-phi);
            path.moveTo((float)x, (float)y);
            path.lineTo((float)p2.x, (float)p2.y);
            x = p2.x + barb*Math.cos(theta+Math.PI+phi);
            y = p2.y + barb*Math.sin(theta+Math.PI+phi);
            path.lineTo((float)x, (float)y);
            return path;
        private Point2D.Double getPoint(double theta, Rectangle r) {
            double cx = r.getCenterX();
            double cy = r.getCenterY();
            double w = r.width/2;
            double h = r.height/2;
            double d = Point2D.distance(cx, cy, cx+w, cy+h);
            double x = cx + d*Math.cos(theta);
            double y = cy + d*Math.sin(theta);
            Point2D.Double p = new Point2D.Double();
            int outcode = r.outcode(x, y);
            switch(outcode) {
                case Rectangle.OUT_TOP:
                    p.x = cx - h*((x-cx)/(y-cy));
                    p.y = cy - h;
                    break;
                case Rectangle.OUT_LEFT:
                    p.x = cx - w;
                    p.y = cy - w*((y-cy)/(x-cx));
                    break;
                case Rectangle.OUT_BOTTOM:
                    p.x = cx + h*((x-cx)/(y-cy));
                    p.y = cy + h;
                    break;
                case Rectangle.OUT_RIGHT:
                    p.x = cx + w;
                    p.y = cy + w*((y-cy)/(x-cx));
                    break;
                default:
                    System.out.println("Non-cardinal outcode: " + outcode);
            return p;
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Pointers());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Preview - "Extract shape from busy background"

    I am having trouble trying to use the "Extract shape from busy background" function in Preview.
    I have checked the help menu and read all the tutorials I can find but can't figure it out.
    It says in the help menu: 1. In the toolbar, choose Extract Shape from the Select pop-up menu.
    I can't find "Select" in any pop-up menus or anywhere that gives me the option to "Extract Shape"
    I went to customize tool bar but I couldn't find any thing.
    Can anyone help me out on this one....
    Thanks
    Kevin

    As nobody seems interested, I've assigned a few duke
    dollars ;)What are we, cheap? - No, just kidding: Duke Dollars are nearly as fun as kittens.
    Anyway: I have some kind of a suggestion, but I must disclaim any notion that I am a 2D expert.
    With that:
    1) Start with an Area created from the Rectangular Shape defined by the bounds of your Image.
    2) One 'row' of pixels at a time, find an x-coordinate where the transparency begins, and the coordinate where it ends.
    3) Subtract this Line Shape from your bounding Area: using Area.subtract(new Area(Line))
    In theory, this leaves you with the Area you desire; and you might be able to convert this into a GeneralPath using the Area's PathIterator.
    I have no idea what you'll end up with! I made this up just by reading the API. I do not know what the resulting GeneralPath would be composed of! It might be nifty or it might suck: If the implementation is capable of optimizing adjacent points then the PathIterator will be reduced somewhat. Otherwise you could end up with a large number of very short Lines and this may not scale to a reasonable size. But you might be able to run a test and see what the implementation is doing.
    Don't send me any Duke Bucks unless it surprisingly works correctly!!!!!!!!!!!!
    And if it does work, let me know! It sounds kind of useful.
    Good luck.
    Steev.

  • Determine whether ellipse perimeter or GeneralPath is in a rectangle

    Hi all,
    I'm making a graphing program in which I can draw a number of shapes and lines (all members of java.awt.geom.*). Also, I have a selection tool. The selection tool draws a Rectangle2D over the canvas, and (in theory) any part of a shape or line which is inside the selection box ought to be selected.
    Making this functionality for lines and rectangles was easy, as I could use the intersectsLine(line) method in Rectangle2D.
    However, doing this for ellipses or GeneralPaths is proving to be much more difficult. As far as I can tell, both intersects(...) methods will return true even if I'm inside the object (I want it only to be true if I'm intersecting with a line itself).
    I was wondering if I could use a PathIterator in some way, since they can both give me a PathIterator? Or is there something else I could use?
    Any help would be very much appreciated!

    If you need to check intersection with the perimeter of the shape then you can do the following,
    Stroke stroke = new BasicStroke(1);
    Shape outline = stroke.createStrokedShape(shape);Then test the 'outline' shape for intersection with your rectangle. Obviously you can adjust the stroke to suit.
    Note that you might want to cache the stroked shapes if you're doing a lot of these tests.

  • Area in units of a GeneralPath

    Is there a method to get the area (in units) of a closed GeneralPath or Area object?

    For simple and convex shapes, work around the edge to create a large number of triangles (with one common point in the interior). Then add these up.
    For simple, but nonconvex shapes ... there's always [Green's theorem|http://en.wikipedia.org/wiki/Planimeter]! Obtain a path iterator and integrate your way around the shape. Good luck with that.
    In "Origin of Species" (written only a few years after the first working planimeter was constructed), Darwin estimates the forrested area of North America by cutting the map out of his atlas and weighing the bits.

Maybe you are looking for

  • Bonjour finds the printer, still can't print

    Ok, here's the situation. I am having no luck with printing from the XP SP2 side of bootcamp. I have the printer connected to an Airport Express (a few years old). The HP printer was purchased with the MBP just a few months ago. Everything works just

  • Can US Apple TV be used in europe?

    I am planning to buy an Apple TV for a relative in Belgium as a gift. Would it work? or is there an european version of Apple tv?

  • HT204053 How do you change your region when iTunes and the App Store keep changing it

    I live in china but I'm from Canada and my iTunes is linked to Canada.  Twice so far this year I have had my iTunes, App Store, and iBooks all convert to the Chinese sites. I am trying to put it back to Canada but for some reason it won't change. My

  • Calling a WSSE Enabled Web Service Through a Java Proxy Class

    I am trying to create a client that can access a WSSE enabled web service through the generated java proxy. For now all I am asking for in the .wsse file is the username and password with the line <token tokenType="username"/>. In the client I am set

  • Phone shuts down. sim code correct.

    I turned my phone off at the airport and somehow(???) got my sim code wrong 3 times. Even tho when it asked me to put in sim, and it was correct, it refused to operate. It got to a point of ' Phone is disabled. Connect to itunes. I had a tech guy fro