Search code examples
javaappletawtgraphics2d

How to make a java.awt Graphics2D string appear in random places in the applet


I started Java a few days ago, and was experimenting and fooling around with some Java codes in a Java tutorial I borrowed from the library.

It told me how to draw a string onto an applet using Graphics2D from java.awt and change its font color, size, type, etc.

Now I challenged myself to make the string appear in random places in the applet. I tried using Math.random() to change the x-y coordinates of the string but the variable type was different and I found myself puzzled. Is there any way to make the string appear in random places every time I open the applet? (I'm going into moving the string with an .awt button later.)

Here is my code:

package game;
import java.awt.*;

public class Javagame extends javax.swing.JApplet{
    public void paint(Graphics screen) {
        Graphics2D screen2D = (Graphics2D) screen;
        Font font = new Font("Arial Black", Font.PLAIN, 20);
        screen2D.setFont(font);
        screen2D.drawString("Hello World!", 50, 50); /*right now it is set at 50, 50
        but I want random variables. Thanks*/

    }
}

Solution

  • You want to use something like:

    screen2D.drawString("Hello World!", 
        (int)(Math.random()*width), 
        (int)(Math.random()*height));
    

    Where width and height are the maximum values of X and Y you want. See this related question: "Generating random numbers in a range."