I am trying to write a program to connect two dots with a line between them. First of all, I would like to say, I know drawline()
function but I am not allowed to use it (this is H.W assignment). So my problem is that,I managed to write code to connect two dots but for some reason whenever I run my program the (0,0) pixel is always turned-on and on my first mouse click the line draws from (0,0)
to the first click coordinates. can some one help me figure out how can I run the application without the (o,o)
pixel turned-on??.
Another thing I want to do its to seperate each one of the lines (two clicks = line, another two clicks = another seperate line) and thats also something I am struggling to implement.
hope my explanation is good enough, Any help would be great! this is my code:
package com.mycompany;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class MousePanel extends JPanel implements MouseListener,ActionListener{
private int x,y,x2,y2,a=1;
public MousePanel(){
super();
addMouseListener(this);
}
public void paint(Graphics g){
int w = x2 - x ;
int h = y2 - y ;
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
int longest = Math.abs(w) ;
int shortest = Math.abs(h) ;
if (!(longest>shortest)) {
longest = Math.abs(h) ;
shortest = Math.abs(w) ;
if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
dx2 = 0 ;
}
int numerator = longest >> 1 ;
for (int i=0;i<=longest;i++) {
g.fillRect(x,y,1,1);
numerator += shortest ;
if (!(numerator<longest)) {
numerator -= longest ;
x += dx1 ;
y += dy1 ;
} else {
x += dx2 ;
y += dy2 ;
}
}
}
public void mouseClicked(MouseEvent mouse){
x=x2;
y=y2;
x2 = mouse.getX();
y2 = mouse.getY();
repaint();
}
public void mouseEntered(MouseEvent mouse){ }
public void mouseExited(MouseEvent mouse){ }
public void mousePressed(MouseEvent mouse){ }
public void mouseReleased(MouseEvent mouse){ }
public static void main(String arg[]){
JFrame frame = new JFrame("MousePanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640,640);
MousePanel panel = new MousePanel();
frame.setContentPane(panel);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}