I am trying to get this code to make a square that will follow your mouse on the y axis. Right now it is just making a new square every time the mouse moves how would I fix this?
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.*;
public class Pong {
public static void main(String args[]) {
Frame f = new Frame("Pong");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new PongField(Color.black), BorderLayout.CENTER);
f.setResizable(false);
f.pack();
f.setVisible(true);
}
}
class PongField extends Canvas {
boolean playing = true;
boolean running = true;
public PongField(Color mainscreen) {
setForeground(mainscreen);
}
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
public void paint(Graphics g) {
while (true) {
Dimension size = getSize();
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
a = MouseInfo.getPointerInfo();
b = a.getLocation();
int x = size.width / 2;
int y = (int) b.getY();
g.fillRect(x / x * 10, y, 10, 75);
g.drawLine(size.width / 2 - 5, 0, size.width / 2 - 5, size.height);
if (y != (int) b.getY())
y = (int) b.getY();
}
}
}
You don’t need a loop in paint() — in fact, it’s a horrible, horrible thing to do, as it otherwise freezes the whole GUI (no other component will be able to paint itself, ever!) Take the “while” loop out, leaving just the body of the loop. Then arrange for paint() to be called as appropriate by adding a
MouseMotionListenerthat callsrepaint(). In the constructor, do something like:That should do it. Now whenever the mouse moves, paint() will be called. Screen erasing will be taken care of for you, automatically.