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

huangapple go评论70阅读模式
英文:

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

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

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

import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
    public void paint(Graphics g) {
        g.drawRect(10, 10, 200, 200);
    }
}

public class DrawRect {
    public static void main(String[] a) {
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setBounds(30, 30, 300, 300);
        window.getContentPane().add(new MyCanvas());
        window.setVisible(true);
    }
}

输出:

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

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

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

 import java.awt.Graphics;

 import javax.swing.JComponent;
 import javax.swing.JFrame;

 class MyCanvas extends JComponent {

 public void paint(Graphics g) {
 g.drawRect (10, 10, 200, 200);  
 }
  }

  public class DrawRect {
 public static void main(String[] a) {
   JFrame window = new JFrame();
  
 
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 window.setBounds(30, 30, 300, 300);
  window.getContentPane().add(new MyCanvas());
   window.setVisible(true);
   }
  }

Output :

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

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

drawRect(int  x, int  y, 
    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://go.coder-hub.com/60691361.html
匿名

发表评论

匿名网友

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

确定