Results 1 to 13 of 13
  1. #1
    Digihash is offline Member
    Join Date
    Feb 2010
    Posts
    5
    Rep Power
    0

    Default Drawing heart for valentine

    Hi,

    This is my first post on this forum. Hello everyone.

    I want to make an application for my girlfriend with some text flashing in the app (with an interval), and a heart that I draw with code. Is this possible to draw a heart with code in java?

    I found this code:
    Java Code:
    public class Heart {
        public static void main(String[] args) {
            StdDraw.setXscale(-1.5, +1.5);
            StdDraw.setYscale(-1.5, +1.5);
            StdDraw.setPenColor(StdDraw.PINK);
    
            // draw diamond
            double[] xs = { -1,  0, 1, 0 };
            double[] ys = {  0, -1, 0, 1 };
            StdDraw.filledPolygon(xs, ys);
    
            // circles
            StdDraw.filledCircle(+0.5, 0.5, 1 / Math.sqrt(2));
            StdDraw.filledCircle(-0.5, 0.5, 1 / Math.sqrt(2));
        }
    }
    The problem is that I don't know how to execute this. StdDraw is a field that has to be made. It doesn't exist yet, but how do you make a draw field?

    Greetings
    Digihash
    Last edited by Digihash; 02-04-2010 at 11:19 PM. Reason: I Found some new code

  2. #2
    mrmatt1111's Avatar
    mrmatt1111 is offline Senior Member
    Join Date
    Aug 2009
    Location
    San Jose, CA, USA
    Posts
    320
    Rep Power
    6

    Default

    This should get you started:

    Java Code:
    public class Heart extends javax.swing.JPanel {
    
       public void paintComponent(java.awt.Graphics g)
       {
          super.paintComponents(g);
    
          java.awt.Graphics2D g2d = (java.awt.Graphics2D)g;
    
          g2d.setColor(java.awt.Color.red);
          g2d.fillOval(25, 25, 50, 50);
    
          //Fill the rest in
          //...
    
          g2d.setColor(java.awt.Color.black);
          g2d.drawString("Blah blah", 50, 50);
       }
    
    
       public static void main(String[] args)
       {
          javax.swing.JFrame frame = new javax.swing.JFrame();
    
          frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
    
          int w = 300;
          int h = 300;
    
          frame.setBounds(200,200,w,h);
          frame.setVisible(true);
          frame.getContentPane().setLayout(null);
    
          Heart heart = new Heart();
          heart.setBounds(0,0,w,h);
    
          frame.getContentPane().add(heart);
       }
    }
    My Hobby Project: LegacyClone

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,455
    Rep Power
    20

    Default

    Java Code:
    new JLabel("<html><h1 style=\"font-size:200; color:red;\">&hearts;</h1></html>")
    ;)

  4. #4
    Digihash is offline Member
    Join Date
    Feb 2010
    Posts
    5
    Rep Power
    0

    Default

    @mrmatt1111:Your is pretty complicated to me, but still thanks for your quick answer. I am now reading a book about 2dgraphics, maybe I'll understand all of it at the end of the book.

    @Darryl.Burke: Thanks for that simple answer, I'll use that. Maybe you know how to make that label flash with an interval, like every 2 seconds it flashes.

    Thanks in advance

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Digihash View Post
    @Darryl.Burke: Thanks for that simple answer, I'll use that. Maybe you know how to make that label flash with an interval, like every 2 seconds it flashes.
    Look into using a Swing Timer for this.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    How about a polar parametric heart?

    Java Code:
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Point2D;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class ValentineHeart extends JPanel {
       
       private static final double MULTIPLIER = 0.3;
       private static final int X_TRANSLATION = (int) (1000 * MULTIPLIER);
       private static final int Y_TRANSLATION = (int) (2 * 850 * MULTIPLIER);
       private static final Dimension APP_SIZE = new Dimension(2 * X_TRANSLATION,
                2 * X_TRANSLATION);
       private static final float STROKE_SIZE = 5;
       List<Point2D> pointsR = new ArrayList<Point2D>();
       
       public ValentineHeart() {
          for (int t = 0; t <= 60; t++) {
             double r = MULTIPLIER * (-t*t +40*t + 1200.0);
             double theta = t * Math.PI / 180;
             double x = r * Math.sin(theta); 
             double y = - r * Math.cos(theta);
             pointsR.add(new Point2D.Double(x, y));
          }
          setPreferredSize(APP_SIZE);
       }
       
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          g2.setStroke(new BasicStroke(STROKE_SIZE));
          g2.setColor(Color.red);
          if (pointsR.size() > 3) {
             Point2D p0 = pointsR.get(0);
             for (int i = 1; i < pointsR.size(); i++) {
                Point2D p1 = pointsR.get(i);
                int x1 = (int) p0.getX();
                int y1 = (int) p0.getY();
                int x2 = (int) p1.getX();
                int y2 = (int) p1.getY();
                g.drawLine(x1 + X_TRANSLATION, y1 + Y_TRANSLATION, x2 + X_TRANSLATION, y2 + Y_TRANSLATION);
                g.drawLine(X_TRANSLATION - x1, y1 + Y_TRANSLATION, X_TRANSLATION - x2, y2 + Y_TRANSLATION);
                p0 = p1;
             }         
          }
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("ValentineHeart");
          frame.getContentPane().add(new ValentineHeart());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    reference: Heart Curve

  7. #7
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    Hm, so no one fancies the ASCII art heart anymore
    Java Code:
    *Created on Feb 6, 2010
     */
    
    
    public class DrawHeart {
    
      public static void main(String[] args) {
        PrintStream out = System.out;
        
        int width = 20;
        int height= 15;
        String[] lines = new String[height];
        
        int p1 = width/2;
        int p2 = width/2;
        int p3 = width/2;
        int p4 = width/2;
        
        boolean topPart = false;
        
        for (int i = height-1; i >= 0; i--) {
          StringBuilder l = new StringBuilder();
          if (p1 == 0) {
            topPart = true;
          }
          if (topPart) {
            int col = 0;
            while (col++ < p1) {
              l.append(" ");
            }
            l.append("*");
            while(col++ < p3) {
              l.append(" ");
            }
            l.append("*");
            if (p4 > p3) {
              while (col++ < p4) {
                l.append(" ");
              }
              l.append("*");
            }
            while (col++ < p2) {
              l.append(" ");
            }
            l.append("*");
            
            p1++;
            p2--;
            p3--;
            p4++;
          }
          else {
            int col = 0;
            while (col++ < p1) {
              l.append(" ");
            }
            l.append("*");
            if (p2 > p1) {
              while (col++ < p2) {
                l.append(" ");
              }
              l.append("*");
            }
            p1--;
            p2++;
          }
          lines[i] = l.toString();
    
        }
        
        for (String line : lines) {
          System.out.println(line);
        }
      }
    }
    Java Code:
        * *       * *
       *   *     *   *
      *     *   *     *
     *       * *       *
    *         *         *
     *                 *
      *               *
       *             *
        *           *
         *         *
          *       *
           *     *
            *   *
             * *
              *
    Long live fixed width fonts!

  8. #8
    Digihash is offline Member
    Join Date
    Feb 2010
    Posts
    5
    Rep Power
    0

    Default

    Woot, this is nice. Thanks guys, I'll use both of those examples, ASCII and normal figures :D

  9. #9
    Digihash is offline Member
    Join Date
    Feb 2010
    Posts
    5
    Rep Power
    0

    Default

    @Fubarable: How can I fill this heart. I'm checking out the code right now and trying to understand everything :D

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Digihash View Post
    @Fubarable: How can I fill this heart. I'm checking out the code right now and trying to understand everything :D
    Hm, I'm not 100% sure, but if it were me, I'd look into possibly using the List of points to create a Polygon Shape. Then I could use the Graphics2D fill method to fill the shape with my color of choice..

  11. #11
    Digihash is offline Member
    Join Date
    Feb 2010
    Posts
    5
    Rep Power
    0

    Default

    OK, I'll try. I'm learning Java at university this year but we haven't learned anything about Graphics and drawing. I'm learning it bit by bit.

  12. #12
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    
    public class Heart extends JPanel {
        CubicCurve2D.Double[] curves = new CubicCurve2D.Double[2];
        Point2D.Double[] points;
        boolean showPath = false;
    
        public Heart() {
            int[][] cds = {
                { 192, 139 }, { 201,  35 }, { 348,  47 }, { 312, 163 },
                { 312, 163 }, { 291, 235 }, { 237, 301 }, { 192, 324 }
            };
            points = new Point2D.Double[cds.length];
            for(int j = 0; j < cds.length; j++) {
                points[j] = new Point2D.Double(cds[j][0], cds[j][1]);
            }
            curves[0] = new CubicCurve2D.Double();
            curves[0].setCurve(points, 0);
            curves[1] = new CubicCurve2D.Double();
            curves[1].setCurve(points, 4);
            setBackground(Color.white);
            new HeartPointMover(this);
        }
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            // Get left half of heart.
            Path2D.Double leftSide = getReflection(w);
            if(!showPath) {
                // Show construction and allow user to drag/print points.
                // Draw vertical construction line at mid-width.
                g2.setPaint(new Color(200,230,210));
                g2.drawLine(w/2, 0, w/2, getHeight());
                // Draw curves.
                g2.setPaint(Color.blue);
                for(int i = 0; i < curves.length; i++) {
                    g2.draw(curves[i]);
                }
                // Connect control points across curve juncture
                // to help position them for smooth connection.
                g2.setPaint(Color.pink);
                g2.draw(new Line2D.Double(points[2], points[5]));
                // Mark curve end and control points.
                for(int j = 0; j < points.length; j++) {
                    mark(g2, j);
                }
                // Draw left half of heart.
                g2.setPaint(Color.pink);
                g2.draw(leftSide);
            } else {
                // Show a path with no construction.
                Path2D.Double path = new Path2D.Double();
                path.append(curves[0], false);
                path.append(curves[1], false);
                path.append(leftSide, false);
                g2.setPaint(Color.blue);
                g2.draw(path);
            }
        }
    
        private Path2D.Double getReflection(int w) {
            Path2D.Double path = new Path2D.Double();
            AffineTransform at = AffineTransform.getTranslateInstance(w,0);
            at.scale(-1,1);
            Path2D.Double p = new Path2D.Double(curves[0]);
            path.append(p.getPathIterator(at), false);
            p = new Path2D.Double(curves[1]);
            path.append(p.getPathIterator(at), false);
            return path;
        }
    
        public void toggleShowPath() {
            showPath = !showPath;
            repaint();
        }
    
        public void setPoint(Point2D.Double p, double x, double y) {
            p.setLocation(x, y);
            if(p.equals(points[3])) {
                points[4].setLocation(x, y);
            }
            setCurves();
        }
    
        private void setCurves() {
            for(int i = 0; i < curves.length; i++) {
                curves[i].setCurve(points, i*4);
            }
            repaint();
        }
    
        private void mark(Graphics2D g2, int index) {
            double x = points[index].x;
            double y = points[index].y;
            int i = (index+1) % 4;
            Color color = (i == 2 || i == 3) ? Color.green.darker() : Color.red;
            g2.setPaint(color);
            g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
        }
    
        public static void main(String[] args) {
            JFrame f = new JFrame("Heart");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new Heart());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }
    
    class HeartPointMover extends MouseAdapter {
        Heart component;
        Point2D.Double selectedPoint;
        Cursor cursor;
        Cursor defaultCursor = Cursor.getDefaultCursor();
        Point2D.Double offset = new Point2D.Double();
        boolean dragging = false;
        final int PROX_DIST = 5;
    
        public HeartPointMover(Heart h) {
            component = h;
            BufferedImage image = getImage();
            Point hotspot = new Point(17,17);
            cursor = Toolkit.getDefaultToolkit()
                            .createCustomCursor(image, hotspot, null);
            component.addMouseListener(this);
            component.addMouseMotionListener(this);
        }
    
        public void mousePressed(MouseEvent e) {
            if(SwingUtilities.isRightMouseButton(e)) {         // show path
                component.toggleShowPath();
            } else if(!component.showPath) {                   // or construction
                if(selectedPoint != null) {                    // drag points
                    offset.x = e.getX() - selectedPoint.x;
                    offset.y = e.getY() - selectedPoint.y;
                    dragging = true;
                } else {                                       // write points
                    printCurvePoints();
                    System.out.println("--------------------------");
                }
            }
        }
    
        private void printCurvePoints() {
            Point2D.Double[] pts = component.points;
            for(int j = 0; j < pts.length; j++) {
                System.out.printf("points[%d] = [%5.1f, %5.1f]%n",
                                   j, pts[j].x, pts[j].y);
            }
        }
    
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        }
    
        public void mouseDragged(MouseEvent e) {
            if(dragging) {
                double x = e.getX() - offset.x;
                double y = e.getY() - offset.y;
                component.setPoint(selectedPoint, x, y);
            }
        }
    
        /** For point selection. */
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            Point2D.Double[] pts = component.points;
            boolean hovering = false;
            for(int j = 0; j < pts.length; j++) {
                if(j == 4) continue;
                if(pts[j].distance(p) < PROX_DIST) {
                    hovering = true;
                    if(selectedPoint != pts[j]) {
                        selectedPoint = pts[j];
                        component.setCursor(cursor);
                        break;
                    }
                }
            }
    
            if(!hovering && selectedPoint != null) {
                selectedPoint = null;
                component.setCursor(defaultCursor);
            }
        }
    
        private BufferedImage getImage() {
            int w = 27, h = 27,
                type = BufferedImage.TYPE_INT_ARGB_PRE;
            BufferedImage image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(new Color(0x333333));
            g2.draw(new Line2D.Double(w/2, 0, w/2, 8));    // n
            g2.draw(new Line2D.Double(0, h/2, 8, h/2));    // w
            g2.draw(new Line2D.Double(w/2, h-8, w/2, h));  // s
            g2.draw(new Line2D.Double(w-8, h/2, w, h/2));  // e
            g2.dispose();
            return image;
        }
    }

  13. #13
    CoderMan is offline Member
    Join Date
    Feb 2010
    Location
    Ross Lunar Capsule 2571
    Posts
    15
    Rep Power
    0

    Default

    Or, of course, you could download a PNG image of a heart, load it as an Image, and draw it to the screen.

    But, of course, I'm sure it will mean a lot more to your girlfriend to know that you spent 3 hours writing 300 lines of code to do the what you could have done in 2 minutes. :rolleyes:
    Last edited by CoderMan; 03-09-2010 at 02:45 AM.

Similar Threads

  1. Drawing staircases
    By GreenRock in forum Java Applets
    Replies: 6
    Last Post: 01-21-2010, 08:20 AM
  2. Drawing Applet
    By Urgle in forum New To Java
    Replies: 6
    Last Post: 11-19-2008, 09:38 AM
  3. Drawing a map
    By Karp in forum AWT / Swing
    Replies: 4
    Last Post: 11-07-2008, 01:26 PM
  4. Problem with 3D drawing.
    By Supamagier in forum Advanced Java
    Replies: 0
    Last Post: 08-31-2008, 01:39 PM
  5. Help with 2-D Drawing
    By Deathmonger in forum New To Java
    Replies: 4
    Last Post: 06-18-2008, 03:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •