Problem creating random lines in Java

0

I made a program that creates a line from two points in random positions in a JFrame. But I realized that when I minimized the window and re-maximized it, I would get a new line generated by two different points from the previous ones. What is going wrong?

@Override
public void paint(Graphics g) {
    super.paint(g);
    g.setColor(Color.red);
    int random1 = (int) (800 * Math.random());
    int random2 = (int) (800 * Math.random());
    int random3 = (int) (800 * Math.random());
    int random4 = (int) (800 * Math.random());
    g.drawLine(random1, random2, random3, random4);
    System.out.println("Random 1: " + random1);
    System.out.println("Random 2: " + random2);
    System.out.println("Random 3: " + random3);
    System.out.println("Random 4: " + random4);
}
    
asked by Mati Bonino 24.11.2018 в 05:29
source

1 answer

0

What you have "wrong" is the initialization of the random within paint , when the GUI is re-dimensioned implicitly a call is made to repaint , which causes that again all your random values are different to those generated before minimizing / maximizing and the line is drawn in a different area of the window.

What you can do is remove int random1 , int random2 ... etc and place them / initialize them in a method different from paint or make them global scope.

I want to say for example the following:

class Back extends javax.swing.JPanel {
   int random1 = (int) (800 * Math.random());
   int random2 = (int) (800 * Math.random());
   int random3 = (int) (800 * Math.random());
   int random4 = (int) (800 * Math.random());

   @Override
   public void paint(Graphics g) {
     super.paint(g);
     g.setColor(Color.red);
     //int random1 = (int) (800 * Math.random());
     //int random2 = (int) (800 * Math.random());
     //int random3 = (int) (800 * Math.random());
     //int random4 = (int) (800 * Math.random());
     g.drawLine(random1, random2, random3, random4);
     System.out.println("Random 1: " + random1);
     System.out.println("Random 2: " + random2);
     System.out.println("Random 3: " + random3);
     System.out.println("Random 4: " + random4);
   }
}

In this way any chart will keep the initial locations, repaint no longer leads to regenerate randoms.

    
answered by 24.11.2018 / 08:24
source