import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SimpleDraw { public static void main(String[] args) { JFrame f = new JFrame("SimpleDraw"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(300, 300); f.setContentPane(new Canvas()); f.setVisible(true); } } // JComponent is a base class for custom components class Canvas extends JComponent { Point M = new Point(); // mouse point Point C = new Point(150, 150); // click point Canvas(){ super(); this.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ C.x = e.getX(); C.y = e.getY(); repaint(); } }); this.addMouseMotionListener(new MouseAdapter(){ public void mouseMoved(MouseEvent e){ M.x = e.getX(); M.y = e.getY(); repaint(); } }); } // custom graphics drawing public void paintComponent(Graphics g) { super.paintComponent(g); // cast to get 2D drawing methods Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(2)); g2.drawLine(C.x, C.y, M.x, M.y); g2.fillOval(M.x - 5, M.y - 5, 10, 10); g2.setColor(Color.RED); g2.fillOval(C.x - 5, C.y - 5, 10, 10); g2.drawString(String.format("%d,%d", C.x, C.y), C.x + 10, C.y + 10); g2.setColor(Color.BLACK); g2.drawString(String.format("%d,%d", M.x, M.y), M.x + 10, M.y + 10); } }