import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class
ID: 3541981 • Letter: I
Question
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class projectheba1 extends Frame implements
MouseListener
{
int upperLeftX, upperLeftY, width, height, x1, y1, x2, y2;
int numpress = 0;
TextField position = new TextField();
private void initializeTextField()
{
position.setLocation(5, 575);
position.setSize(70, 20);
position.setBackground(Color.white);
add(position);
}
protected void displayMouseCoordinates(int X, int Y)
{
position.setText("[" + String.valueOf(X)+ "," + String.valueOf(Y)+"]");
}
public void mousePressed(MouseEvent event)
{
upperLeftX= 0; upperLeftY =0; width = 0; height = 0;
x1 = event.getX();
y1 = event.getY();
x2 = event.getX();
y2 = event.getY();
Graphics g = getGraphics();
displayMouseCoordinates(event.getX(), event.getY());
numpress = numpress +1;
}
public void paint(Graphics g) {
initializeTextField();
addMouseListener(this);
displayMouseCoordinates(x1, y1);
int p1 = 0, p2 = 0, p3 = 0, p4 = 0;
if(numpress == 1)
{
p1 = x1;
p2 = y1;
}
else
{
p3 = x2;
p4 = y2;
}
Line2D line1 = new Line2D.Double(p1, p2, p3, p4);
Stroke drawingStroke = new BasicStroke(2);
Graphics2D graph = (Graphics2D)g;
graph.setStroke(drawingStroke);
graph.setPaint(Color.red);
graph.draw(line1);
}
public static void main(String args[]) {
Frame frame = new projectheba1();
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
frame.setSize(800, 600);
frame.setVisible(true);
}
}
what in the world is wrong with this code, it runs and i can see the points of the mouse for x and y but i cant seem to save them in variables and use them to calculate what i need
Explanation / Answer
One big mistake I can see is if you are implementing the mouseListener, then you have to implement all the methods of it. You have implemented just 1 which is mousePressed. You have to implement remaining 4. Even if you are not doing anything, you can keep the body of the methods blank. These methods are
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.