JPanel 圆形
时间: 2023-08-11 13:07:38 浏览: 70
要在 JPanel 上绘制一个圆形,可以使用 Graphics 类的 drawOval() 方法。以下是一个简单的例子:
```
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class CirclePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawOval(10, 10, 50, 50);
}
}
```
在这个例子中,我们继承了 JPanel 类并重写了它的 paintComponent() 方法。在该方法中,我们首先调用了父类的 paintComponent() 方法来保证 JPanel 能够正常工作。然后,我们设置了画笔颜色为红色,并使用 drawOval() 方法绘制了一个圆形。drawOval() 方法的四个参数分别是圆形左上角的 x 坐标、左上角的 y 坐标、圆形的宽度和高度。在这个例子中,我们绘制了一个左上角坐标为 (10, 10),宽度和高度都为 50 像素的圆形。最后,我们将 CirclePanel 加入到 JFrame 中即可看到结果。
相关问题
Java画一个圆形
可以使用Java的绘图类Graphics2D来画圆形,具体代码如下:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Circle extends JPanel {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// 设置抗锯齿
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 设置画笔颜色为红色
g2d.setColor(Color.RED);
// 画圆形,起始点为(50, 50),直径为100
g2d.drawOval(50, 50, 100, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Circle");
frame.add(new Circle());
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
运行这个Java程序,就可以看到一个红色圆形。
java将图片变成圆形
可以使用Java的Graphics2D类的clip()和drawOval()方法将图片变成圆形。
下面是一个简单的示例代码:
```java
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CircularImage extends JPanel {
private BufferedImage image;
public CircularImage() {
try {
// 读取图片
image = ImageIO.read(new File("example.png"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
// 抗锯齿
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 将图片剪切成圆形
int width = getWidth();
int height = getHeight();
g2d.clipOval(0, 0, width, height);
g2d.drawImage(image, 0, 0, width, height, this);
// 绘制圆形边框
g2d.drawOval(0, 0, width-1, height-1);
g2d.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Circular Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setContentPane(new CircularImage());
frame.setVisible(true);
}
}
```
这个示例代码将一个名为"example.png"的图片变成了一个圆形,并在一个窗口中显示。你可以根据自己的需要修改代码。