简体   繁体   中英

Plotting random points in Java using 2D Graphics

I am beginner to java Graphics , I have been trying to plot random dots on JFrame but don't know why when I compile there is nothing on Frame , for me logic is fine + no error. Can someone help me whats wrong here

public class parent extends JPanel {    

    public void PaintComponent (Graphics g)     
    {
        super.paintComponent(g);
        Graphics2D g2d  = (Graphics2D) g;
        g2d.setColor(Color.blue);
        Dimension size = getSize();
        Insets  insets= getInsets();
        int w =  size.width - insets.left - insets.right;
        int h =  size.height - insets.top - insets.bottom;
        Random r = new Random();

        for (int i=0; i<1000; i++) {
           int x = Math.abs(r.nextInt()) % w;
           int y = Math.abs(r.nextInt()) % h;
           g2d.drawLine(x, y, x, y);
        }
    }


    public static void main(String[] args) 
    {
        JFrame frame = new JFrame("Points");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new parent());
        frame.setSize(250, 200);
        frame.setVisible(true);
     }
} 

Well is it PaintComponent or should it be paintComponent ? I think I know which one the Java developers would choose.

Note that this is a perfect bug that @Override in annotation would catch in Eclipse.

From your code, you are using the DrawLine to draw from (x, y) to (x, y). Which would be a single pixel. And you have set the Color Blue. Therefore it will not be very visible, regardless of the color.

But aside from that, your loop calculates the X and Y values based upon the Random Number R, and yet R is never re-calculated as a new Random Number (you set it once before the loop, and never reset it). So that will then re-plot the same point over-and-over again 1,000 times.

If you put the Random Number Calculation inside the loop, and have it draw a circle with a radius of, oh, 5-10 pixels, around your random point, it will be much more visible. And then you should be on the way to accomplishing your goal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM