如何用java在应用程序顶部绘制一个矩形



如何在java中向应用程序顶部绘制矩形?通常drawRect方法会向底部绘制,我试图使用负数,但这不适用于

Graphics g = p.getGraphics();
g.fillRect(50, 200,50,100);

在矩形中,X和Y坐标表示左上角。然后,从定义点开始绘制长度和宽度。您的示例绘制了一个矩形,左上角为50200,宽度为50,高度为100,两者都以正方向远离这些点。如果你想要一个50200代表左下角的矩形,只需从y坐标(200)中减去高度,并将其用作起始y:

Graphics g = p.getGraphics();
g.fillRect(50, 100, 50, 100);

为了解决您的例子,请尝试这样的方法(我只使用矩形对象,而不是实际填充图形):

int baseline = 200;
Rectangle rect1 = new Rectangle(50, baseline - 100, 50, 100);
Rectangle rect2 = new Rectangle(150, baseline - 50, 50, 50);
Rectangle rect3 = new Rectangle(250, baseline - 80, 50, 80);

在图形对象上用这些尺寸填充矩形后,将有三个每个宽度为50的矩形,间隔50,底部都在y=200线上。

Java的Graphics类假设原点(0, 0)在帧的左上角,即(1, 1)(0, 0)的右侧。这与数学相反,在数学中,标准笛卡尔平面中的原点在左下角,(1, 1)(0, 0)的上方和右侧。

此外,Java不允许对宽度和高度使用负值。这就产生了一种特殊的逻辑,这种逻辑通常会将矩形与正常的正维矩形区别对待。

要得到您想要的东西,首先将您对Java的Graphics坐标系中的y坐标的想法颠倒过来。正y是向下的,而不是向上的(尽管正x仍然是正确的,就像标准的笛卡尔图一样)。

也就是说,drawRectfillRect的字段是:

  1. 矩形左上角的x坐标
  2. 矩形左上角的y坐标
  3. 矩形的正宽度
  4. 矩形的正高度

Zoe的回答展示了一个很好的例子,说明了如何获得你想要的东西,我只是觉得你可能想要一个更彻底的解释,解释为什么"drawRect方法接近底部。">

运行它。。在小程序窗口上的任意方向上拖放鼠标。。看看发生了什么。。。希望你能从中得到一些想法…

//Simulation of the desktop screen
package raj_java;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DesktopDemo extends Applet implements MouseListener, MouseMotionListener {
int x1, y1, x2, y2;
Image img;
public void init() {
setSize(1200, 700);
setVisible(true);
img = getImage(getCodeBase(), "Nature.jpg");
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent me) {
//blank
}
public void mouseExited(MouseEvent me) {
//blank
}
public void mouseClicked(MouseEvent me) {
//blank
}
public void mouseReleased(MouseEvent me) {
Graphics g = getGraphics();
g.drawImage(img, 0, 0, 1200, 700, this);
}
public void mouseMoved(MouseEvent me) {
//blank
}
public void mousePressed(MouseEvent me) {
x1 = me.getX();
y1 = me.getY();
}
public void mouseDragged(MouseEvent me) {
x2 = me.getX();
y2 = me.getY();
repaint();
}
public void paint(Graphics g) {
g.drawImage(img, 0, 0, 1200, 700, this);
g.setColor(new Color(10, 99, 126));
g.drawLine(x1, y1, x2, y1);
g.drawLine(x2, y1, x2, y2);
g.drawLine(x2, y2, x1, y2);
g.drawLine(x1, y2, x1, y1);
g.setColor(new Color(193, 214, 220, 70));
int width = Math.abs(x2 - x1);
int height = Math.abs(y2 - y1);
if(x2 < x1) {
g.fillRect(x2, y1, width, height);
}else if(y2 < y1) {
g.fillRect(x1, y2, width, height);
}else {
g.fillRect(x1, y1, width, height);
}
}
}

相关内容

最新更新