Drawing over an image in java

Muneeb Mughal :

I'm developing an application for a client and it requires me to draw some lines over an image. I searched over stackoverflow for some help and managed to draw line using JLayeredPane but the previous lines fade whenever i click to make new lines. Here's the code snippet (not exactly mine).

public class Test2
{
private JFrame frame = new JFrame();
private JLayeredPane lpane = new JLayeredPane();
private JPanel panel1 = new MyPanel("C:\\Users\\mumm\\Desktop\\map.jpg");
private JPanel panel2 = new JPanel();

public Test2()
{
    frame.setPreferredSize(new Dimension(600, 400));
    frame.setLayout(new BorderLayout());
    frame.add(lpane, BorderLayout.CENTER);
    lpane.setBounds(0, 0, 600, 400);
    panel1.setBounds(0, 0, 600, 400);
    panel1.setOpaque(true);

    panel2.setBounds(200, 100, 100, 100);
    panel2.setOpaque(false);
    lpane.add(panel1, 0, 0);
    lpane.add(panel2, 1, 0);
    frame.pack();
    frame.setVisible(true);
}


class MyPanel extends JPanel  implements MouseListener, MouseMotionListener 
{
    private String imageFile;
    private int index = 0;
    private Point[] arr = new Point[100000];

    public MyPanel(String imageFile) 
    {
        this.imageFile = imageFile;
        this.addMouseListener(this);
        this.addMouseMotionListener(this);
    }
    @Override
    protected void paintComponent(Graphics g) {

        Image img = new ImageIcon(imageFile).getImage();
        g.drawImage(img, 0, 0, this);

        for (int i = 0; i < index - 1; i++)

            g.drawLine(arr[i].x, arr[i].y, arr[i + 1].x, arr[i + 1].y);
    }


    @Override
    public void mousePressed(MouseEvent e)
    {
        arr[index] = new Point(e.getX(), e.getY());
        index++;
        System.out.println(index);
        repaint();
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
        arr = new Point[100000];
        index = 0;
    }

    @Override
    public void mouseDragged(MouseEvent e)
    {
        arr[index] = new Point(e.getX(), e.getY());
        index++;
        System.out.println(index);
        repaint();
    }

}


public static void main(String[] args) {
    new Test2();
}

Basically what i want is something like this.

Required

Any sort of help would be appreciated.

Johan Tidén :

I think it's because you wipe the array in mouseReleased, which is triggered after the last drag event has drawn the line.

You would see this if you call repaint from mouseReleased.

Stop clearing the array and it should be fine.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=388909&siteId=1