Drawing a line with a mouse in JAVA

Every time I start to make something of my own, in the process of making THE BIG THING, I like to discover little tricks that help me to make the whole thing up. So, here I deliver my technique to draw a line in JAVA by mouse. Pretty easy thing though. I can’t make it to save all the lines it draws on the JPanel as it reapaints the whole JFrame when the paintComponent method is called every time. But I’m thinking of using an array to store all the co-ordinates to make it able to draw multiple lines at a time. If I’m successful u would see the whole code later. Now whatever I came up with is here….

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

public class ConnectLines extends JPanel
{
private int x, y, x1=0, y1=0;

public ConnectLines()
{

addMouseListener(

new MouseAdapter() {

@Override
public void mouseClicked(MouseEvent event)
{

x=event.getX();
y=event.getY();
}
}
);

addMouseMotionListener(

new MouseMotionAdapter() {

@Override
public void mouseMoved(MouseEvent event)
{
x1=event.getX();
y1=event.getY();
repaint();
}
});
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(x, y, x1, y1);
}

}

//the main fuction
import java.awt.BorderLayout;
import javax.swing.JFrame;

public class AppTest
{
public static void main(String args[])
{
JFrame app= new JFrame(“testing drag line”);

ConnectLines connectLines=new ConnectLines();
app.add(connectLines,BorderLayout.CENTER);

app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(400, 300);
app.setVisible(true);
}

}

hope u would like it!

Advertisements