Results 1 to 2 of 2
  1. #1
    DamienCurr is offline Member
    Join Date
    Jul 2009
    Posts
    1
    Rep Power
    0

    Default Major help needed with drawing rectangles using JFrame and Mouse Events

    Good evening!

    So, I've been working on this program that draws rectangles using JFrame and implementing MouseListener and MouseMotionListener. You should be able to click and drag the mouse, drawing a rectangle, no matter where in the frame you start out. I have not had much luck getting it to work. The frame will display, but I am unable to draw the rectangles. It also produces one error when I compile, "JDrawRect.java:81: cannot find symbol symbol : method paintComponent(java.awt.Graphics) location: class javax.swing.JFrame super.paintComponent(g);". When the program runs, in addition to the frame loading, there is an additional error, "Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container".

    What am I doing wrong?

    Damien



    Java Code:
    package project2;
    
    // JDrawRect.java
    // Demonstrating mouse events.
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
    
        public class JDrawRect extends JFrame
        implements MouseListener, MouseMotionListener {
       //imported variables follow...
          private int pointCount = 0;
          private Point points[]  = new Point[100];
          private Point points2[] = new Point[100];
          private Point start = new Point();
          private Point end   = new Point();
          Rectangle rect = new Rectangle();
       //imported variables end
       
       //private static final long serialVersionUID = 1L;
          private JLabel mousePosition;
       
       // set up GUI and register mouse event handlers
           public JDrawRect()
          {
             super( "Drawing Rectangles" );
         
             mousePosition = new JLabel();
             mousePosition.setHorizontalAlignment(SwingConstants.CENTER);
             getContentPane().add( mousePosition, BorderLayout.CENTER );
         
             
             addMouseListener( this );        // listens for own mouse and
             addMouseMotionListener( this );  // mouse-motion events
         
             //setSize( 400, 300 );
             //setVisible( true );
          }
       
       // MouseListener event handlers
       // handle event when mouse released immediately after press
           public void mouseClicked( MouseEvent event ){}
       
       // handle event when mouse pressed
           public void mousePressed( MouseEvent event )
          {
             start = event.getPoint();
          }
       
       // handle event when mouse released after dragging
           public void mouseReleased( MouseEvent event )
          {
             points[pointCount] = start;
             points2[pointCount] = event.getPoint();
             pointCount++;
             rect.setFrameFromDiagonal(start, start);
             repaint();
          }
       
       // handle event when mouse enters area
           public void mouseEntered( MouseEvent event ){}
       
       // handle event when mouse exits area
           public void mouseExited( MouseEvent event ){}
       
       // MouseMotionListener event handlers
       // handle event when user drags mouse with button pressed
           public void mouseDragged( MouseEvent event )
          {
             end = event.getPoint();
             rect.setFrameFromDiagonal(start, end);
             repaint();
          }
       
       // handle event when user moves mouse
           public void mouseMoved( MouseEvent event ){}
       
       
           public void paintComponent(Graphics g)
          {
             super.paintComponent(g);
             Graphics2D g2 = (Graphics2D)g;
             g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            // Draw line being dragged.
             g2.setPaint(Color.red);
             g2.draw(rect);
            // Draw lines between points in arrays.
             g2.setPaint(Color.blue);
             Rectangle r = new Rectangle();
             for (int i =0; i < pointCount; i++)
             {
                r.setFrameFromDiagonal(points[i], points2[i]);
                g2.fill(r);
             }
          }
           public static void main( String args[] )
          {
             //JDrawRect application = new JDrawRect();
             //application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         
             JDrawRect test = new JDrawRect();
             JFrame f = new JFrame();
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             f.add(test);
             f.setSize(400,400);
             f.setLocation(200,200);
             f.setVisible(true);
         
          }
       
       } // end class JDrawRect

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

    Default

    For one thing, you're trying to draw in the JFrame itself and trying to override a non-existent method, paintComponent. JFrames don't have a paintComponent method since they do not inherit from JComponent. To find out for yourself, just place an @Override annotation above your paintComponent method and see that it will cause an error:

    Java Code:
      @Override  // this causes a compile error
      public void paintComponent(Graphics g) {
      //...
    This is the same reason that calling super.paintComponent(g) fails here as there simply is no super for this method in a JFrame.

    Far better is to do the drawing in a JPanel or JComponent, and override paintComponent in this class. Then create an instance of this and place it in your JFrame's contentPane. The Sun Swing graphics tutorial should explain this in more detail and is required reading I should think.

    Other suggestions:
    1) Don't have your main drawing class implement MouseListener and MouseMotionListener. Instead I'd create a private inner class that extends MouseAdapter.
    2) Instead of a fixed array of 100 Point objects, consider using the more flexible ArrayList<Point>, or perhaps even ArrayList<Rectangle2D>

    For instance,
    Java Code:
    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.*;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.*;
    
    public class JDrawRect2 extends JPanel {
      private static final Color RECT_FILL_COLOR = Color.blue.brighter().brighter();
      private static final Color RECT_DRAW_COLOR = Color.blue.darker();
      private static final Color DRAGGING_RECT_COLOR = Color.pink;
      private static final Dimension MAIN_SIZE = new Dimension(800, 600);
      private List<Rectangle2D> rectList = new ArrayList<Rectangle2D>();
      private Rectangle2D draggingRect = null;
      
      public JDrawRect2() {
        setPreferredSize(MAIN_SIZE);
        MouseAdapter mouseAdapter = new MyMouseAdapter();
        addMouseListener(mouseAdapter);
        addMouseMotionListener(mouseAdapter);
      }
      
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        Graphics2D g2 = (Graphics2D)g;
        for (Rectangle2D rect : rectList) {
          g2.setColor(RECT_FILL_COLOR);
          g2.fill(rect);
          g2.setColor(RECT_DRAW_COLOR);
          g2.draw(rect);
        }
        if (draggingRect != null) {
          g2.setColor(DRAGGING_RECT_COLOR);
          g2.draw(draggingRect);      
        }
      };
      
      // in case the MouseAdapter is not an inner class
      public void addRectangle(Rectangle2D r) {
        rectList.add(r);
      }
      
      public void setDraggingRect(Rectangle2D r) {
        draggingRect = r;
      }
      
      private class MyMouseAdapter extends MouseAdapter {
        private Point start = null;
        
        @Override
        public void mousePressed(MouseEvent e) {
          start = e.getPoint();
        }
        
        @Override
        public void mouseReleased(MouseEvent e) {
          addRectangle(createRect2D(e));
          setDraggingRect(null);
          JDrawRect2.this.repaint();
        }
        
        @Override
        public void mouseDragged(MouseEvent e) {
          setDraggingRect(createRect2D(e));
          JDrawRect2.this.repaint();      
        }
    
        private Rectangle2D createRect2D(MouseEvent e) {
          Point end = e.getPoint();
          int width = Math.abs(start.x - end.x);
          int height = Math.abs(start.y - end.y);
          int x = Math.min(start.x, end.x);
          int y = Math.min(start.y, end.y);
          Rectangle2D r = new Rectangle2D.Double(x, y, width, height);
          return r;
        }
      }
    
      private static void createAndShowUI() {
        JFrame frame = new JFrame("JDrawRect2");
        frame.getContentPane().add(new JDrawRect2());
        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();
          }
        });
      }
    }
    Last edited by Fubarable; 07-16-2009 at 02:47 PM.

Similar Threads

  1. Mouse events, are they best or only way to go?
    By dbashby in forum New To Java
    Replies: 2
    Last Post: 04-10-2009, 04:34 PM
  2. Need help with looping mouse Events.
    By busdude in forum New To Java
    Replies: 1
    Last Post: 04-08-2009, 08:25 PM
  3. Replies: 1
    Last Post: 10-24-2008, 04:00 AM
  4. Menu item not working properly for mouse events
    By Preethi in forum New To Java
    Replies: 1
    Last Post: 09-23-2008, 08:56 AM
  5. Demonstration of mouse events
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 07-11-2008, 04:45 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
  •