本例主要是通过使用坐标轴平移,图形旋转和获得随机数等技术来绘制艺术图案。通过重写JPanel类中的paint()方法,并在该方法中使用Graphics2D类中的translate(),setColor(),ratate()和draw()方法来实现的。具体代码如下:
1. 创建一个ArtDesignPanel类,继承JPanel类,来进行图形的绘制
1 package com.example.artdesign.ui; 2 3 import java.awt.Color; 4 import java.awt.Graphics; 5 import java.awt.Graphics2D; 6 import java.awt.geom.Ellipse2D; 7 import java.util.Random; 8 9 import javax.swing.JPanel; 10 11 /*** 12 * 创建内部面板类 13 * @author lenovo' 14 * 15 */ 16 public class ArtDesignPanel extends JPanel{ 17 18 @Override 19 public void paint(Graphics g) { //重写paint方法 20 // TODO Auto-generated method stub 21 Graphics2D g2 = (Graphics2D)g; //获得Graphics2D对象 22 Ellipse2D.Float ellipse = new Ellipse2D.Float(-80, 5, 160, 10); //创建椭圆对象 23 g2.translate(160, 90); //平移坐标轴 24 25 Random random = new Random(); //获得随机数 26 int R = random.nextInt(256); //随机产生颜色的R值 27 int G = random.nextInt(256); //随机产生颜色的G值 28 int B = random.nextInt(256); //随机产生颜色的B值 29 30 Color color = new Color(R,G,B); //创建颜色对象 31 g2.setColor(color); //指定颜色 32 g2.draw(ellipse); //绘制椭圆 33 34 int i = 0; 35 while (i < 100) { 36 37 R = random.nextInt(256); //随机产生颜色的R值 38 G = random.nextInt(256); //随机产生颜色的G值 39 B = random.nextInt(256); //随机产生颜色的B值 40 41 color = new Color(R,G,B); 42 43 g2.setColor(color); 44 g2.rotate(10); //旋转画布 45 g2.draw(ellipse); //绘制椭圆 46 47 i++; 48 } 49 50 } 51 }
2. 创建一个ArtDesignFrame类,继承JFrame类,来加载ArtDesignPanel窗体。
package com.example.artdesign.ui; import java.awt.Dimension; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; public class ArtDesignFrame extends JFrame{ /** * */ private static final long serialVersionUID = -1760723807752896879L; public ArtDesignFrame() { // TODO Auto-generated constructor stub this.add(new ArtDesignPanel()); this.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowClosing(WindowEvent arg0) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent arg0) { // TODO Auto-generated method stub System.exit(0); } @Override public void windowActivated(WindowEvent arg0) { // TODO Auto-generated method stub } }); this.setVisible(true); } public static void main(String[] args) { ArtDesignFrame frame = new ArtDesignFrame(); frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); frame.setSize(360, 360); } }
运行截图如下:
文本摘自:《JAVA开发实例1200例》---王家林。