Results 1 to 3 of 3
  1. #1
    Yoruichi is offline Member
    Join Date
    Mar 2009
    Posts
    4
    Rep Power
    0

    Default Drawing a shape on an image

    Hello,

    I am trying to draw a shape over an image, but I'm having trouble with the size drawing the size of the rectangle. When the user clicks the mouse, the program is supposed to save both the starting points and endpoints then draw in a rectangle. However, it looks like the rectangle is doubling in size. Can someone please have a look at the code and tell me where I'm going wrong?

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    import javax.swing.JColorChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    
    public class Test {
    
    	public static void main(String[] args)
    	{
    		EventQueue.invokeLater(new Runnable()
    			{
    				public void run()
    				{
    					MyFrame frame = new MyFrame();
    					frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				
    				}
    			});
    	}
    }
    
    class MyFrame extends JFrame
    {
    	private JPanel imagePanel;
    	private BufferedImage image;
    	private Dimension dim;
    	private Point2D.Double startPoint = new Point2D.Double();
    	private Point2D.Double endPoint = new Point2D.Double();
    	
    	public MyFrame()
    	{
    		setTitle("Lab 7");
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
            setResizable(false);
    		
    		try{
    			image = ImageIO.read(new File("simple.png"));
    			
    		} catch (Exception e){
    			e.printStackTrace();
    		}
    		
    		imagePanel = new JPanel(){
    			
    			public void paint(Graphics g)
    			{
    				super.paint(g);
    				g.drawImage(image, 0, 0, null);
    			}
    		};
    		
    		imagePanel.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
    		add(imagePanel);
    		addMouseListener(new MouseHandler());
    		addMouseMotionListener(new MouseSelect());
    		setFocusable(true);
    		addKeyListener(new KeyHandler());
    		pack();
            setVisible(true);
    	}
    	
    	class MouseHandler extends MouseAdapter
    	{
    		public void mousePressed(MouseEvent e)
    		{
    			startPoint.x = e.getX();
    			startPoint.y = e.getY();	
    		}
    	/*	
    		public void mouseReleased(MouseEvent e)
    		{
    			endPoint.x = e.getX();
    			endPoint.y = e.getY();
    		}
    		*/
    		
    	}
    	
    	class KeyHandler extends KeyAdapter
    	{
    		public void keyPressed(KeyEvent e) 
    		{
    			if(e.getKeyCode() == (KeyEvent.VK_X) )//| KeyEvent.VK_CONTROL))
    			{
    				System.out.println("CTRL X HAS BEEN CLICKED   start  "+startPoint.getX() + "  "+startPoint.getY() + "     end  "+endPoint.getX()+  "  " +endPoint.getY());
    				 Graphics2D g = (Graphics2D) getGraphics();
    				 g.setColor(Color.BLACK);
    				 g.fillRect((int)startPoint.getX(), (int)startPoint.getY(), (int)endPoint.getX(), (int)endPoint.getY());	
    			}
    		}	
    	}
    	
    
    	class MouseSelect extends MouseMotionAdapter {
    		@Override
    		public void mouseDragged(MouseEvent e) {
    			super.mouseDragged(e);
    			Graphics2D g = (Graphics2D) getGraphics();
    			g.setXORMode(Color.WHITE);
    			Rectangle2D.Double r = new Rectangle2D.Double(startPoint.x,startPoint.y, endPoint.x - startPoint.x, endPoint.y- startPoint.y);
    			g.draw(r);
    			endPoint.x = e.getX();
    			endPoint.y = e.getY();
    			r = new Rectangle2D.Double(startPoint.x, startPoint.y, endPoint.x- startPoint.x, endPoint.y - startPoint.y);
    			g.draw(r);
    		}
    
    	}
    	
    }

    Thanks for any help.

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

    Default

    I would advise you to avoid getting a Graphics object via a component's getGraphics method. Yes, this will get you a valid graphics object, but it will only be valid up until the component repaints, and then *poof* your drawing disappears. Much better is to do passive drawing within the paintComponent method. If you study the Sun tutorials on graphics, it will show you exactly what I mean and how to correct your problem.

    Best of luck.

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

    Default

    for instance
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.File;
    
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Test
    {
    
      public static void main(String[] args)
      {
        EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            MyFrame frame = new MyFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
          }
        });
      }
    }
    
    class MyFrame extends JFrame
    {
      private static final String IMAGE_PATH = "src/yr2009/m02/c/images/Bullfight.jpg";
      private JPanel imagePanel;
      private BufferedImage image;
      private Dimension dim;
      private Point2D.Double startPoint = new Point2D.Double();
      private Point2D.Double endPoint = new Point2D.Double();
      private Rectangle2D rect2D;
      private boolean fill = false;
    
      public MyFrame()
      {
        setTitle("Lab 7");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
    
        try
        {
          image = ImageIO.read(new File(IMAGE_PATH));
    
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
    
        imagePanel = new JPanel()
        {
    
          public void paintComponent(Graphics g)
          {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, null);
            if (rect2D != null)
            {
              Graphics2D g2 = (Graphics2D)g;
              g2.setXORMode(Color.white);
              g2.draw(rect2D);
              if (fill)
              {
                g2.setColor(Color.black);
                g2.fill(rect2D);
              }
            }
          }
        };
    
        imagePanel.setPreferredSize(new Dimension(image.getWidth(), image
            .getHeight()));
        add(imagePanel);
        imagePanel.addMouseListener(new MouseHandler());
        imagePanel.addMouseMotionListener(new MouseSelect());
        setFocusable(true);
        addKeyListener(new KeyHandler());
        pack();
        setVisible(true);
      }
    
      class MouseHandler extends MouseAdapter
      {
        public void mousePressed(MouseEvent e)
        {
          startPoint.x = e.getX();
          startPoint.y = e.getY();
        }
      }
    
      class KeyHandler extends KeyAdapter
      {
        public void keyPressed(KeyEvent e)
        {
          if (e.getKeyCode() == (KeyEvent.VK_X))// | KeyEvent.VK_CONTROL))
          {
            fill = !fill;
            imagePanel.repaint();
    //        System.out.println("CTRL X HAS BEEN CLICKED   start  "
    //            + startPoint.getX() + "  " + startPoint.getY() + "     end  "
    //            + endPoint.getX() + "  " + endPoint.getY());
    //        Graphics2D g = (Graphics2D) getGraphics();
    //        g.setColor(Color.BLACK);
    //        g.fillRect((int) startPoint.getX(), (int) startPoint.getY(),
    //            (int) endPoint.getX(), (int) endPoint.getY());
          }
        }
      }
    
      class MouseSelect extends MouseMotionAdapter
      {
        @Override
        public void mouseDragged(MouseEvent e)
        {
          super.mouseDragged(e);
          rect2D = new Rectangle2D.Double(startPoint.x, startPoint.y,
              endPoint.x - startPoint.x, endPoint.y - startPoint.y);
          imagePanel.repaint();
    //      g.draw(r);
          endPoint.x = e.getX();
          endPoint.y = e.getY();
    //      r = new Rectangle2D.Double(startPoint.x, startPoint.y, endPoint.x
    //          - startPoint.x, endPoint.y - startPoint.y);
    //      g.draw(r);
        }
    
      }
    
    }

Similar Threads

  1. Drawing on an image
    By kratra in forum New To Java
    Replies: 0
    Last Post: 02-06-2009, 09:58 PM
  2. Need help getting java drawing match to image.
    By kiduut in forum New To Java
    Replies: 9
    Last Post: 12-28-2008, 02:55 PM
  3. [SOLVED] Image drawing, saving
    By Goseph in forum Java 2D
    Replies: 2
    Last Post: 12-21-2008, 08:36 PM
  4. Shape drawing applet not working...
    By evapisces in forum Java Applets
    Replies: 0
    Last Post: 11-18-2008, 12:46 AM
  5. drawing an image to an offscreen image
    By hunterbdb in forum Java 2D
    Replies: 9
    Last Post: 10-30-2008, 07:17 PM

Posting Permissions

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