-2

I have been trying for the last two days to draw objects on my JPanel. The code was running when I tried to draw objects on the JPanel when it was not placed in JTabbedPane. But it is hectic for me now. Kindly help me.

registering JPanel with MouseMotionListener

panel[i].addMouseMotionListener(this);

adding panel to JTabbedPane

tp.addTab("Tab1",panel[i]);

mouseDragged event has the following code

public void mouseDragged(MouseEvent e) {
   x = e.getX();
   y = e.getY();
   repaint();
}

mouseReleased event

public void mouseReleased(MouseEvent e) {
    x1 = e.getX();
    y1 = e.getY();
    repaint();
}

paint function ( that must be called automatically) has the following lines

public void paint( Graphics g )
{
  super.paint(g); 
  // I even tried to add the following line but it didn't work too
  /// g=panel[tp.getSelectedIndex()].getGraphics();
  Graphics2D gtd=(Graphics2D) g;
  gtd.fillOval(x, y, x1-x, y1-y); //x1-x: For width of Oval; y1-y: for height
}
Noam Hacker
  • 4,671
  • 7
  • 34
  • 55

1 Answers1

1

x1 and y1 will always equal x and y, because a mouse release always occurs in (or very near) the location of the most recent mouse drag. Which means your oval always has a width of zero and a height of zero.

If your goal is to create an oval the size of the area the user has dragged, you must save the location of a mousePressed event. You should then update the opposing corner (x1 and y1 in your case) in mouseDragged.

You should not update any coordinates in a mouseReleased event. Instead, you should keep a boolean flag (in a private field) indicating that a drag is in progress. Set it to true when mousePressed occurs and set it to false when mouseReleased occurs. Your mouseDragged method should only update the oval's coordinates while that flag is set.

VGR
  • 40,506
  • 4
  • 48
  • 63
  • I also added mousePrssed event. Sorry, I missed that code. public void mousePressed(MouseEvent e) { x = e.getX(); y = e.getY(); repaint(); } But it didn't work too. I just made another class extending from JPanel and copied the same code, it works there. Thanks for your time to answer me..:) – user3274506 May 05 '14 at 11:35