package forum;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.event.MouseInputAdapter;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add( new DrawPanel() );
frame.setBounds( 20, 20, 500, 500 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible( true );
}
}
class DrawPanel extends JComponent{
public static final float MOD_X = 30.0f;
public static final float MOD_Y = 30.0f;
private Vector lines = new Vector();
public DrawPanel(){
Listener listener = new Listener();
addMouseListener( listener );
addMouseMotionListener( listener );
}
public synchronized void paintComponent( Graphics g ){
int width = getWidth();
int height = getHeight();
g.setColor( Color.BLACK );
g.fillRect( 0, 0, width, height );
g.setColor( Color.GRAY );
for( int x = 0; x <= width; x += (int)(MOD_X) )
g.drawLine( x, 0, x, height );
for( int y = 0; y <= height; y += (int)(MOD_Y) )
g.drawLine( 0, y, width, y );
for( int i = 0, n = lines.size(); i<n; i++ ){
((Line)lines.get( i )).paint( g, MOD_X, MOD_Y );
}
}
private class Listener extends MouseInputAdapter{
private Line current;
public Listener(){}
public void mousePressed(MouseEvent e) {
Point pos = transform( e.getX(), e.getY() );
current = new Line( pos.x, pos.y );
lines.add( current );
repaint();
}
public void mouseDragged(MouseEvent e) {
if( current != null ){
current.setEndPos( transform( e.getX(), e.getY() ) );
repaint();
}
}
public void mouseReleased(MouseEvent e) {
mouseDragged( e );
current = null;
}
public Point transform( int x, int y ){
return new Point( Math.round(x / MOD_X), Math.round( y / MOD_Y ) );
}
}
}
class Line{
private int x1, y1, x2, y2;
private Color color;
public Line( int x, int y ){
x1 = x;
y1 = y;
x2 = x;
y2 = y;
color = new Color( (int)(Math.round( Math.random() * 255)),
(int)(Math.round( Math.random() * 255)),
(int)(Math.round( Math.random() * 255)));
}
public void setEndPos( Point pos ){
x2 = pos.x;
y2 = pos.y;
}
public void paint( Graphics g, float modX, float modY ){
g.setColor( color );
g.drawLine( Math.round( modX * x1 ),
Math.round( modY * y1 ),
Math.round( modX * x2 ),
Math.round( modY * y2 ));
}
}