我试图在矩形内构建矩形。矩形"墙壁"应处于特定位置,高度为bg.getheight() - 地面。getheight()。由于某种原因,矩形"墙"仍然延伸至小程序的底部。所有其他值(例如宽度和位置)都可以正常工作。如果我减去静态120,则有300个高度小程序,但是地面的值实际上是60,如果我减去60,它仍然会一直延伸到边界。我对不一致感到困惑。
import javax.swing.JApplet;
import java.awt.*;
public class House_JM extends JApplet {
public void paint(Graphics page) {
Rectangle ground = new Rectangle(0, (int) (getSize().height * .8), getSize().width,
(int) (getSize().height * .2));
Rectangle bg = new Rectangle(0, 0, getSize().width, (int) (getSize().height * .8));
page.setColor(Color.green);
page.fillRect((int) ground.getX(), (int) ground.getY(), (int) ground.getWidth(), (int) ground.getHeight());
page.setColor(Color.blue);
page.fillRect((int) bg.getX(), (int) bg.getY(), (int) bg.getWidth(), (int) bg.getHeight());
Rectangle walls = new Rectangle((int) (bg.getWidth() / 2 - bg.getWidth() * .1), (int) (bg.getHeight() * .5),
(int) (bg.getWidth() * .4), (int) ((bg.getHeight() - ground.getHeight())));
page.setColor(Color.red);
page.fillRect((int) walls.getX(), (int) walls.getY(), (int) walls.getWidth(), (int) walls.getHeight());
System.out.println(bg.getHeight());
}
}
答案的核心已在评论中给出:"您的数学已经关闭"。您确实错了的计算,没有任何意义。
这是一个示例,显示了您可能要实现的结果:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JApplet;
public class House_JM extends JApplet {
@Override
public void paint(Graphics g) {
Graphics2D page = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
Rectangle2D ground = new Rectangle2D.Double(
0, h * 0.8, w, h * 0.2);
Rectangle2D bg = new Rectangle2D.Double(
0, 0, w, h * 0.8);
Rectangle2D walls = new Rectangle2D.Double(
bg.getWidth() * 0.5 - bg.getWidth() * 0.1,
bg.getHeight() * 0.5,
bg.getWidth() * 0.4,
h * 0.4);
page.setColor(Color.green);
page.fill(ground);
page.setColor(Color.blue);
page.fill(bg);
page.setColor(Color.red);
page.fill(walls);
System.out.println(bg.getHeight());
}
}
请注意, walls
矩形的高度必须是小程序乘以0.4的高度,因为在 bg.getHeight() * 0.5
处启动,这是小程序时时间0.4的高度,地板的高度高度为小程序的高度0.2倍。