1

I am a newbie in java and also in java Graphics. I wrote a simple code for sketching but it is not working well. when i drag my mouse little quickly some pixels are missed. Here is my code..

package test;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;

public class testdraw extends JPanel{
    public int x1;
    public int y1;
    public int x2;
    public int y2;
    public testdraw(){
    addMouseMotionListener(new MouseAdapter() {

        public void mouseDragged(MouseEvent e){
            x2=e.getX();
            y2=e.getY();
            repaint();
            x1=x2;
            y1=y2;

        }


    });

}
    public void paintComponent(Graphics g){

        Graphics2D g2=(Graphics2D)g;
        g2.drawLine(this.x1, this.y1,this.x2,this.y2);;

    }
}   

Main class..

package test;

import javax.swing.JFrame;
public class testdrawmain {

    public static void main(String args[]){
        JFrame frame=new JFrame();
        testdraw td=new testdraw();
        frame.add(td);
        frame.setSize(350, 350);
        frame.setVisible(true);

   }

}

Could anybody please tell me what is wrong. Please suggest me. Thanks in advance.

sovon
  • 877
  • 2
  • 12
  • 28

1 Answers1

2
        x2=e.getX();
        y2=e.getY();
        repaint();
        x1=x2;
        y1=y2;

x1 and x2 will be the same after this regardless of where you call repaint() -- not very useful.

Instead do the assignment before getting the mouse position.

        x1=x2;
        y1=y2;
        x2=e.getX();
        y2=e.getY();
        repaint();

If you want to draw all points, then create an ArrayList<Point>, add to the list in the mouse motion listener and in paintComponent iterate through the list.

Also:

  • paintComponent should be protected, not public.
  • You must call the super's paintComponent method in your own override.
  • Please have a look at this example.

Edit
Your comment:

My application can draw like paint...so when drag mouse every time start and end coordinate will change

Then you have two options: using a ArrayList<ArrayList<Point>> or drawing on a BufferedImage and displaying the BufferedImage within your paintComponent method.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373