Java绘制艺术图形

时间:2023-03-09 18:53:40
Java绘制艺术图形

本例主要是通过使用坐标轴平移,图形旋转和获得随机数等技术来绘制艺术图案。通过重写JPanel类中的paint()方法,并在该方法中使用Graphics2D类中的translate(),setColor(),ratate()和draw()方法来实现的。具体代码如下:

1. 创建一个ArtDesignPanel类,继承JPanel类,来进行图形的绘制

 package com.example.artdesign.ui;

 import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.util.Random; import javax.swing.JPanel; /***
* 创建内部面板类
* @author lenovo'
*
*/
public class ArtDesignPanel extends JPanel{ @Override
public void paint(Graphics g) { //重写paint方法
// TODO Auto-generated method stub
Graphics2D g2 = (Graphics2D)g; //获得Graphics2D对象
Ellipse2D.Float ellipse = new Ellipse2D.Float(-80, 5, 160, 10); //创建椭圆对象
g2.translate(160, 90); //平移坐标轴 Random random = new Random(); //获得随机数
int R = random.nextInt(256); //随机产生颜色的R值
int G = random.nextInt(256); //随机产生颜色的G值
int B = random.nextInt(256); //随机产生颜色的B值 Color color = new Color(R,G,B); //创建颜色对象
g2.setColor(color); //指定颜色
g2.draw(ellipse); //绘制椭圆 int i = 0;
while (i < 100) { R = random.nextInt(256); //随机产生颜色的R值
G = random.nextInt(256); //随机产生颜色的G值
B = random.nextInt(256); //随机产生颜色的B值 color = new Color(R,G,B); g2.setColor(color);
g2.rotate(10); //旋转画布
g2.draw(ellipse); //绘制椭圆 i++;
} }
}

ArtDesignPanel

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);
} }

ArtDesignFrame

运行截图如下:

Java绘制艺术图形

文本摘自:《JAVA开发实例1200例》---王家林。