The Graphcis context Graphcis already been translated to match the x / y location that the component should appear in the parent container, which means that the upper left corner of the Graphics context in the paintComponent method is actually 0x0.
You need to determine some size for the ball, you draw at 10x10, which assumes your step component should return preferredSize from 10x10
public Dimension getPreferredSize() { return new Dimension(10, 10); }
You will be responsible for providing the appropriate layout details to the ball when it is added to the parent container ...
public void mouseClicked(MouseEvent evt) { Point p = evt.getPoint(); Ball ball = new Ball(); Dimension size = ball.getPreferredSize(); ball.setBounds(new Rectangle(p, size)); add(ball); }
This of course assumes that you have a null layout for the parent container
UPDATED
Sort of...

public class PaintBalls { public static void main(String[] args) { new PaintBalls(); } public PaintBalls() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new Board()); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class Board extends JPanel { public Board() { setLayout(null); setBackground(Color.WHITE); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Point p = e.getPoint(); Ball ball = new Ball(); Dimension size = ball.getPreferredSize(); px -= size.width / 2; py -= size.height / 2; ball.setBounds(new Rectangle(p, size)); add(ball); repaint(); } }); } } public class Ball extends JPanel { public Ball() { setOpaque(false); } @Override public Dimension getPreferredSize() { return new Dimension(10, 10); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.RED); g2d.fillOval(0, 0, 10, 10); g2d.dispose(); } } }
source share