java绘制矩形
时间: 2023-08-30 17:05:50 浏览: 44
在Java中,绘制矩形可以使用 Graphics 类的 drawRect() 方法。下面是一个简单的示例:
```java
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RectangleExample extends JPanel {
public void paint(Graphics g) {
super.paint(g);
g.drawRect(50, 50, 100, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rectangle Example");
RectangleExample rectangleExample = new RectangleExample();
frame.add(rectangleExample);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
```
在这个示例中,我们继承了 JPanel 类并重写了它的 paint() 方法。在这个方法中,我们调用了 Graphics 类的 drawRect() 方法,传递了矩形的起始坐标(50,50)以及宽度和高度(100,100)。最后,我们将这个 JPanel 添加到 JFrame 中,并显示这个窗口。当运行这个程序时,它会显示一个带有一个矩形的窗口。