我试图让我的代码绘制 10 个矩形,每个矩形都有随机的位置和大小。
问题是,由于某种原因,它只绘制了一个矩形,而从不绘制其他 9 个矩形。
我正在使用Math.random
。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Punto1
extends JPanel {
public static void main(String[] args) {
System.out.println("Estoy en el main");
JFrame frame = new JFrame("Soy una ventana :D");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1280, 720);
frame.setVisible(true);
frame.setLocation(400, 200);
frame.setLocationRelativeTo(null);
frame.add(new Punto1());
}
public Punto1() {
}
public void paintComponent(Graphics g) {
g.setColor(Color.BLUE);
/*if(x1 != 0 && y1 != 0 && x2 != 0 && y2 !=0){
g.drawLine(x1,y1,x2,y2);
*/
rectangulo(g);
}
public void rectangulo(Graphics g) {
for (int i = 0; i < 10; i++) {
int x = (int) Math.random() * 1120 + 75;
int y = (int) Math.random() * 680 + 75;
int width = (int) Math.random() * 960 + 50;
int height = (int) Math.random() * 960 + 50;
g.setColor(Color.BLUE);
g.drawRect(x, y, width, height);
}
}
}
最佳答案
(int)Math.random()
正在将值截断为 int
,好的,但是 random
返回一个介于 0
& 1
,这意味着任何小于 1
的值都将是 0
, 0 x 1120
是 0
加上 75
,即 75
,因此您的代码在同一位置绘制 10 个矩形
二、可能的解决方案:
一个...
执行后将计算结果转换为int
:
int x = (int)(Math.random() * 1120 + 75)
这将确保计算是针对 double
基值完成的,并在计算结果后截断为 int
两个
利用 Graphics 2D API 并使用支持 double 值的 Rectangle2D
...
double x = Math.random() * 1120 + 75;
double y = Math.random() * 680 + 75;
double width = Math.random() * 960 + 50;
double height = Math.random() * 960 + 50;
Rectangle2D rect = new Rectangle2D.Double(x, y, width, height);
((Graphics2D)g).draw(rect);
旁注...
此外,除非您有特殊原因要这样做,否则您应该最后调用 setVisible
- 这会导致更少的问题
JFrame frame = new JFrame("Soy una ventana :D");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1280,720);
frame.add(new Punto1());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
最后(不,真的;))
由于窗口在各种操作系统上的工作方式,面板不太可能与窗口大小相同,事实上,在大多数情况下,它更小。
在这种情况下,您应该避免依赖魔数(Magic Number)并使用已知值
double x = Math.random() * getWidth() + 75;
double y = Math.random() * getHeight() + 75;
double width = Math.random() * (getWidth() / 2.0) + 50;
double height = Math.random() * (getHeight() / 2.0) + 50;
Rectangle2D rect = new Rectangle2D.Double(x, y, width, height);
((Graphics2D)g).draw(rect);
关于java - 带图形的循环 - 生成图形时的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49332106/