Make a object when pressed follow mouse pointer, java [closed]

One way is to make your Ball class an actual Swing component. Then you can use the ComponentMover class.


how do you make a class into a swing component

Basically, you move your draw(…) code into the paintComponent() method of JComponent. Here is a simple example that does all the custom painting for you because the painting is based on a Shape object. You would still need to modify the code to paint the “number”.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;

public class ShapeComponent extends JComponent
    Shape shape;

    public ShapeComponent(Shape shape)
        this.shape = shape;
        setOpaque( false );

    public Dimension getPreferredSize()
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.width, bounds.height);

    protected void paintComponent(Graphics g)
        Graphics2D g2d = (Graphics2D)g;

        g2d.setColor( getForeground() );
        g2d.fill( shape );

    public boolean contains(int x, int y)
        return shape.contains(x, y);

    private static void createAndShowUI()
        ShapeComponent ball = new ShapeComponent( new Ellipse2D.Double(0, 0, 50, 50) );
        ball.setSize( ball.getPreferredSize() );
        ball.setLocation(10, 10);

        ShapeComponent square = new ShapeComponent( new Rectangle(30, 30) );
        square.setSize( square.getPreferredSize() );
        square.setLocation(50, 50);

        JFrame frame = new JFrame();
        frame.setSize(200, 200);

        MouseListener ml = new MouseAdapter()
            public void mouseClicked( MouseEvent e )
                System.out.println( "clicked " );

        ball.addMouseListener( ml );
        square.addMouseListener( ml );

    public static void main(String[] args)
        EventQueue.invokeLater(new Runnable()
            public void run()

The main difference between this approach and trashgod’s suggestion to use an Icon is that mouse events will only be generated when the mouse in over the ball, not the rectangular corners of the ball since the contains(...) method respects the shape of what you are drawing.

Browse More Popular Posts

Leave a Comment