Hello! I`m working on a project that allow the users to draw shapes, but for some reason i can`t get the coоrdinates of the mouse, if i write the coordinates of shapes the will draw the shape with the coordinates and sizes I choose. Here is the code i wrote so far.
Interface:
Code:
Interface:
Java:
import java.awt.*;
import java.awt.event.*;
public interface PLShape {
public abstract void drawShape();
}
Code:
Java:
import java.awt.*;
import java.awt.event.*;
public class Kursova extends Frame implements ActionListener {
int x,y,x1,y1;
public Kursova() {
x=y=x1=y1=0;
Frame f=new Frame("Kursova");
f.setSize(700,500);
MyMouseListener listener = new MyMouseListener();
f.addMouseListener(listener);
f.addMouseMotionListener(listener);
NepalenChetir obj = new NepalenChetir();
f.add(obj);
obj.drawShape();
f.setVisible(true);
f.addWindowListener(new WindowAdapter () {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
} //end of constructor Kursova
public void setStartPoint(int x, int y) {
this.x = x;
this.y = y;
}
public void setEndPoint(int x, int y) {
x1 = (x);
y1 = (y);
}
// MyMouseListener class
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
setStartPoint(e.getX(), e.getY());
}
public void mouseDragged(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
repaint();
}
public void mouseReleased(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
repaint();
}
} // end of class MyMouseListener
// The class that used to draw shape
class NepalenChetir extends Panel implements PLShape {
//int x,y,x1,y1;
public void drawPerfectRect(Graphics g, int x, int y, int x1, int y1) {
int px = Math.min(x,x1);
int py = Math.min(y,y1);
int pw=Math.abs(x-x1);
int ph=Math.abs(y-y1);
g.drawRect(px, py, pw, ph);
}
public void paint(Graphics g) {
super.paint(g);
drawPerfectRect(g,x,y,x1,y1);
// g.drawRect(10,20,200,150);
// if i remove the comment of comment of g.drawRect(10,20,200,150);
//the program will draw the shapes with this sizes
}
public void drawShape() {repaint();}
}
public static void main(String[] args) {
new Kursova();
}
}
Last edited: