我该如何在Java应用程序中向上绘制一个矩形?通常,drawRect方法是向下绘制的。我尝试使用负数,但这样做不起作用。
Graphics g = p.getGraphics();
g.fillRect(50, 200,50,100);
我该如何在Java应用程序中向上绘制一个矩形?通常,drawRect方法是向下绘制的。我尝试使用负数,但这样做不起作用。
Graphics g = p.getGraphics();
g.fillRect(50, 200,50,100);
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直线上。
运行它... 在应用程序窗口中向任何方向拖放鼠标...看看发生了什么... 希望你能从中得到一些想法...
//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);
}
}
}