如何在Java中创建一个矩形?

huangapple 未分类评论72阅读模式
英文:

How to make a Rect in Java?

问题

我已经在互联网上扫描了半个小时,而且人们建议的矩形方法不起作用,所以我想知道你们会建议什么。

英文:

I have been scanning the internet for half an hour and the Rects people suggest do not work so I wanted to know what you guys would suggest.

答案1

得分: 0

以下是您要求的翻译内容:

这里有一个由二维网格构成的简单代码

  1. import java.awt.Graphics;
  2. import javax.swing.JComponent;
  3. import javax.swing.JFrame;
  4. class MyCanvas extends JComponent {
  5. public void paint(Graphics g) {
  6. g.drawRect(10, 10, 200, 200);
  7. }
  8. }
  9. public class DrawRect {
  10. public static void main(String[] a) {
  11. JFrame window = new JFrame();
  12. window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  13. window.setBounds(30, 30, 300, 300);
  14. window.getContentPane().add(new MyCanvas());
  15. window.setVisible(true);
  16. }
  17. }

输出:

如何在Java中创建一个矩形?

否则,可以使用 Graphics 对象的 drawRect() 方法。该方法如下:

  1. drawRect(int x, int y, int width, int height)

它使用当前的画笔颜色绘制矩形的轮廓。矩形的左边和右边边缘分别位于 x 和 x + width 处。矩形的顶部和底部边缘分别位于 y 和 y + height 处。

该方法也可用于绘制正方形。该小程序在整个绘图区域周围绘制一个矩形,然后在中心放置另一个矩形。

英文:

The simple code in here which is made by a 2D grid

  1. import java.awt.Graphics;
  2. import javax.swing.JComponent;
  3. import javax.swing.JFrame;
  4. class MyCanvas extends JComponent {
  5. public void paint(Graphics g) {
  6. g.drawRect (10, 10, 200, 200);
  7. }
  8. }
  9. public class DrawRect {
  10. public static void main(String[] a) {
  11. JFrame window = new JFrame();
  12. window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  13. window.setBounds(30, 30, 300, 300);
  14. window.getContentPane().add(new MyCanvas());
  15. window.setVisible(true);
  16. }
  17. }

Output :

如何在Java中创建一个矩形?

Otherwise use the drawRect() method of a Graphics object. This method looks like:

  1. drawRect(int x, int y,
  2. int width, int height)

It draws the outline of a rectangle using the current pen color. The left and right edges of the rectangle are at x and x + width respectively. The top and bottom edges of the rectangle are at y and y + height respectively.

This method is also used to draw a square. This applet draws a rectangle around the entire drawing area, then puts another rectangle in the center.

huangapple
  • 本文由 发表于 2020年3月15日 17:17:37
  • 转载请务必保留本文链接:https://java.coder-hub.com/60691361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定