核心代码:
package swing0401;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.TextAttribute;
import java.awt.geom.Arc2D;
import java.awt.geom.Path2D;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JPanel;
public class MyPanel extends JPanel
{
public MyPanel()
{
}
@Override
protected void paintComponent(Graphics g)
{
int width=this.getWidth();
int height=this.getHeight();
Graphics2D g2d=(Graphics2D)g;
//平滑绘制
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(Color.WHITE);
g2d.fillRect(0, 0, width, height);
//直线与圆弧连接构成不规则形状
int x=50,y=50;
Rectangle r1=new Rectangle(x,y,100,100);
Rectangle r2=new Rectangle(x+100,y,100,100);
//arc1左侧弧形 arc2右侧弧形
Arc2D arc1=new Arc2D.Double(r1,90,180,Arc2D.OPEN);
Arc2D arc2=new Arc2D.Double(r2,270,180,Arc2D.OPEN);
//构造一条闭合路径
Path2D outline=new Path2D.Double();
outline.append(arc1, true);
outline.append(arc2, true);//true表示自动连接上一条线的终点和下一条线的起点
outline.closePath(); //闭合(自动连接最后一个点和最开始的点)
g2d.setPaint(Color.GREEN);
g2d.fill(outline);
}
}