简体   繁体   English

如何使java.awt Graphics2D字符串出现在applet中的随机位置

[英]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. 几天前,我启动了Java,并且在我从库中借来的Java教程中尝试和研究一些Java代码。

It told me how to draw a string onto an applet using Graphics2D from java.awt and change its font color, size, type, etc. 它告诉我如何使用java.awt中的Graphics2D在applet上绘制字符串,并更改其字体颜色,大小,类型等。

Now I challenged myself to make the string appear in random places in the applet. 现在,我向自己发起挑战,要求该字符串出现在applet中的随机位置。 I tried using Math.random() to change the xy coordinates of the string but the variable type was different and I found myself puzzled. 我尝试使用Math.random()更改字符串的xy坐标,但是变量类型不同,我感到困惑。 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.) (我稍后将使用.awt按钮移动字符串。)

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*/

    }
}

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. 其中width和height是所需的X和Y的最大值。 See this related question: " Generating random numbers in a range. " 请参阅以下相关问题:“ 生成范围内的随机数。

You could try using the random class: 您可以尝试使用随机类:

Random r = new Random();
int x = r.nextInt(100);
int y = r.nextInt(100);

This will generate a random integer between 0 and the value specified. 这将生成一个介于0和指定值之间的随机整数。

From memory, Math.ramdom() returns a double value 0-1 . 从内存中, Math.ramdom()返回一个双Math.ramdom()0-1 The position parameters will require a int . 位置参数将需要一个int

You need to cast the double value to an int . 您需要将double值转换为int

screen2D.drawString("Hello World!", (int)(Math.round(Math.random() * getWidth()), (int)(Math.round(Math.random() * getWidth()));

Normally, if you do (int)doubleValue , it will simply trim of the trailing decimal values. 通常,如果您执行(int)doubleValue ,它将简单地修剪尾随的十进制值。 This might be a good, this might be a bad thing. 这可能是一件好事,这可能是一件坏事。 I tend to round the value first, but that's just me. 我倾向于先舍入价值,但这就是我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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