java实现绘制空心封闭半圆,空心圆形,空心矩形 ,空心三角形,空心梯形
时间: 2023-11-20 07:40:31 浏览: 113
以下是Java实现绘制空心封闭半圆、空心圆形、空心矩形、空心三角形、空心梯形的示例代码:
1. 绘制空心封闭半圆
```
import java.awt.Graphics;
import javax.swing.JPanel;
public class HalfCirclePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(getWidth(), getHeight()) / 2 - 10;
g.drawArc(centerX - radius, centerY - radius, radius * 2, radius * 2, 0, 180);
}
}
```
2. 绘制空心圆形
```
import java.awt.Graphics;
import javax.swing.JPanel;
public class CirclePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(getWidth(), getHeight()) / 2 - 10;
g.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
}
}
```
3. 绘制空心矩形
```
import java.awt.Graphics;
import javax.swing.JPanel;
public class RectanglePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 10;
int y = 10;
int width = getWidth() - 20;
int height = getHeight() - 20;
g.drawRect(x, y, width, height);
}
}
```
4. 绘制空心三角形
```
import java.awt.Graphics;
import javax.swing.JPanel;
public class TrianglePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xPoints = {getWidth() / 2, 10, getWidth() - 10};
int[] yPoints = {10, getHeight() - 10, getHeight() - 10};
g.drawPolygon(xPoints, yPoints, 3);
}
}
```
5. 绘制空心梯形
```
import java.awt.Graphics;
import javax.swing.JPanel;
public class TrapezoidPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x1 = getWidth() / 4;
int x2 = getWidth() * 3 / 4;
int y1 = 10;
int y2 = getHeight() - 10;
int width1 = getWidth() / 2 - 20;
int width2 = getWidth() / 2 + 20;
int height = getHeight() - 20;
int[] xPoints = {x1, x2, x2 - width2 / 2, x1 + width1 / 2};
int[] yPoints = {y1, y1, y2, y2};
g.drawPolygon(xPoints, yPoints, 4);
}
}
```
以上示例代码均用Java Swing编写,可以在Java图形界面中运行。
阅读全文