I just don't see how the paint()
or paintComponent()
is being called here. This is from an old youtube video back in 2011; the comment section of that video didn't help. I was expecting this code to call repaint()
in the mousePressed()
method, but it didn't, and it just works.
This is the youtube video: https://www.youtube.com/watch?v=PrPwCKr6WNI
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
public class JavaApplication17 extends JFrame {
int GWIDTH = 800;
int GHEIGHT = 600;
int x, y;
private Image dbImage;
private Graphics dbg;
public JavaApplication17() {
setSize(GWIDTH, GHEIGHT);
setTitle("Game");
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(new Mouse());
x = 15;
y = 15;
}
public class Mouse extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
int xCoord = e.getX();
int yCoord = e.getY();
x = xCoord + 7;
y = yCoord + 7;
}
}
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.fillOval(x, y, 15, 15);
repaint();
}
public static void main(String[] args) {
JavaApplication17 main = new JavaApplication17();
}
}