So the essence is as follows:
A new component is created that draws a triangle:

import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.Random; public class Triangle extends Component { @Override public void paint(Graphics g) { Random rn = new Random(); Color c = new Color(rn.nextInt(256), rn.nextInt(256), rn.nextInt(256)); Graphics2D g2d = (Graphics2D) g; // холст для рисования int nPoints = 3; int[] xPoints = new int[nPoints + 1]; int[] yPoints = new int[nPoints + 1]; for (int i = 0; i < nPoints; i++) { double angle = 2 * Math.PI * i / nPoints; xPoints[i] = (int) (150 + 175 * Math.sin(angle)); yPoints[i] = (int) (100 - 100 * Math.cos(angle)); } g2d.setColor(c); g2d.fillPolygon(xPoints, yPoints, nPoints); //repaint(); //если раскомментировать - треугольник неистово мигает в основном окне. } } 

A triangle is created and added to the window pane by pressing the button:

 Triangle t = new Triangle(); t.setSize(new Dimension(500, 500)); t.setLocation(new Point((jPanel1.getWidth() - 260) / 2, (jPanel1.getHeight() - 200) / 2)); t.setVisible(true); jPanel1.add(t); 

And another button changes the background of the panel:

 Random rn = new Random(); Color c2 = new Color(rn.nextInt(256), rn.nextInt(256), rn.nextInt(256)); jPanel1.setBackground(c2); 

And the following happens:
When you click on the drawing button of a triangle, a triangle is drawn, when pressed again, it changes the background (in essence, a new object is drawn, we create a new object, and there the background is random).
When you click on the change of the background of the panel - the background color and the panel and ... triangle (sic) change.
Under the debugger you can see that the paint method is called again.

Questions: what dick? Why it happens? Is this normal? How to fix it?

  • Isn't paint invoked every time an object is redrawn? - user31238
  • one
    this is normal. paint is called whenever you need to paint an object. When you change the background, you need to redraw the entire panel, and all its child components (triangle). Since the color you choose in paint , it changes. Take out the color and coordinates of the vertices in the class fields, and set in the constructor. - zRrr
  • @zRrr thanks! You can arrange it in response, it all worked. - Ep1demic

0