I want to learn Swing . I write the code that should draw the circles on the coordinates of the mouse click. Circle instances with ั… and ัƒ coordinates ั… which are determined when the mouse is pressed, should be entered into an array of objects. Then JPanel should be redrawn. In a loop, the Circle methods return coordinates, and the circles should be drawn. How to make the program work correctly?

 import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Main{ public static void main(String[] args){ JFrame f = new JFrame(); f.setContentPane(new TestPanel()); f.setSize(600, 500); f.setResizable(false); f.setTitle("TEST"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } } class TestPanel extends JPanel{ LinkedList<Circle> circles = new LinkedList<Circle>(); Random r = new Random(); public TestPanel(){ addMouseListener(new MouseAdapter(){ public void MouseClicked(MouseEvent e){ circles.add(new Circle(e.getX(), e.getY(), r.nextInt(51)+30, new Color(r.nextInt(128), r.nextInt(128), r.nextInt(128), r.nextInt(128)+100))); repaint(); } }); } public void paintComponent(Graphics g){ super.paintComponent(g); for(Circle c : circles){ g.setColor(c.getColor()); g.fillOval(c.getX(), c.getY(), c.getSize(), c.getSize()); } } } import java.awt.Color; public class Circle{ private int x; private int y; private int size; private Color color; public Circle(int x, int y, int s, Color c){ this.x = x; this.y = y; size = s; color = c; } public int getX(){return x;} public int getY(){return y;} public int getSize(){return size;} public Color getColor(){return color;} } 
  • if you use the Override annotation, then such errors will be caught by the compiler. - Mikhail Vaysman

1 answer 1

Your problem is that you override the MouseClicked method, and the MouseAdapter has only the mouserClicked method (with a small letter)

  • Oh I am noodle! There generally initially mousePressed() thought of. Probably when the documentation dug - changed. Now everything is working - Nikita