不规则形状的绘制主要运用Paint2D类:
moveTo:绘制起点
lineTo:点之间连线
注意g2d.draw(outline)与g2d.fill(outline);的区别
g2d.draw(outline):边框
g2d.fill(outline):填充
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.font.TextAttribute;
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);
//创建一个path
Path2D outline=new Path2D.Double();
outline.moveTo(50, 10); //起点
outline.lineTo(150, 60);//直接连接到下一点
outline.lineTo(100, 120);
outline.lineTo(40, 100);
outline.lineTo(10, 40);
outline.closePath(); //收尾闭合
Color fillColor=Color.GREEN;
g2d.setPaint(fillColor);
g2d.fill(outline);
//g2d.draw(outline);
}
}
package swing0401;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFrame extends JFrame
{
public MyFrame(String title)
{
super(title);
//ContentPane
JPanel root=new MyPanel();
this.setContentPane(root);
root.setLayout(new BorderLayout());
}
}
package swing0401;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyDemo
{
private static void createGUI()
{
// JFrame指一个窗口,构造方法的参数为窗口标题
JFrame frame = new MyFrame("Swing Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口的其他参数,如窗口大小
frame.setSize(500, 300);
// 显示窗口
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createGUI();
}
});
}
}