import java.awt.Image; import java.awt.Graphics; import java.awt.Color; import java.awt.Font; import java.awt.event.MouseMotionListener; import java.awt.event.MouseEvent; import java.awt.Graphics2D; // Used for anti-aliasing import java.awt.RenderingHints; // Used for anti-aliasing import javax.swing.JFrame; public class GraphicsMoveObjectWithMouseAndJFrame extends JFrame implements MouseMotionListener { private Image image; private int width = 400, height = 400; private int dotX = 200, dotY = 200, dotSize = 50; public static void main(String[] args) { // Create an instance of the 'GraphicsMoveObjectWithMouseAndJFrame' class new GraphicsMoveObjectWithMouseAndJFrame(); } // Constructor public GraphicsMoveObjectWithMouseAndJFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(width, height); setTitle("Object Movement with a Mouse on a JFrame"); setLocationRelativeTo(null); setResizable(false); setVisible(true); addMouseMotionListener(this); } // Make sure the red dot is always positioned under the mouse pointer public void mouseMoved(MouseEvent event) { dotX = (int) event.getPoint().getX(); dotY = (int) event.getPoint().getY(); repaint(); } // Redraw the red dot, even if the user holds down a mouse button public void mouseDragged(MouseEvent event) { mouseMoved(event); } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { // Prepare to create the image on a separate 'Image' instance; this // will prevent flickering while the mouse is being moved around // the frame by using a "buffer" on which the frame image will // first be drawn before it is displayed to the user image = createImage(width, height); Graphics graphics = image.getGraphics(); // This line causes graphics and text to be rendered with anti-aliasing // turned on, making the overall display look smoother and cleaner ((Graphics2D) graphics).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Reset the frame background so that previous instances of the // red dot are not left behind and visible on the frame graphics.setColor(Color.BLACK); graphics.fillRect(0, 0, width, height); // Add the text instructions to the buffer graphics.setColor(Color.WHITE); graphics.setFont(new Font("Helvetica", Font.BOLD, 16)); graphics.drawString("Move the mouse inside the frame...", 66, 40); // Add the red dot in the correct location (under the mouse pointer) graphics.setColor(Color.RED); graphics.fillOval(dotX - dotSize / 2, dotY - dotSize / 2, dotSize, dotSize); // Display (Draw) the buffered image on the frame g.drawImage(image, 0, 0, null); } }