四叶玫瑰线的图形设计
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RoseJFrame extends JFrame implements ActionListener
{
private RoseCanvas rose; //自定义画布组件
private JButton button_color; //选择颜色按钮
public RoseJFrame()
{
super("四叶玫瑰线"); //框架边布局
Dimension dim=getToolkit().getScreenSize(); //获得屏幕分辨率
this.setBounds(dim.width/4,dim.height/4,dim.width/2,dim.height/2);//窗口居中
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel jpanel=new JPanel(); //面板流布局,居中
this.getContentPane().add(jpanel,"North");
button_color=new JButton("选择颜色");
jpanel.add(button_color);
button_color.addActionListener(this);
rose=new RoseCanvas(Color.red); //创建自定义画布组件
this.getContentPane().add(rose,"Center");
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) //单击事件处理方法
{
Color c=JColorChooser.showDialog(this,"选择颜色",Color.blue);
//弹出JColorChooser颜色选择对话框,返回选中颜色
rose.setColor(c);
rose.repaint(); //重画
}
public static void main(String arg[])
{
new RoseJFrame();
}
}
class RoseCanvas extends Canvas implements ComponentListener//画布组件
{
private Color color; //颜色
public RoseCanvas(Color color)
{
this.setColor(color);
this.addComponentListener(this); //画布注册组件组件监听器
}
public void setColor(Color color)
{
this.color=color;
}
public void paint(Graphics g) //在Canvas上作图
{
int x0=this.getWidth()/2; //(x0,y0)是组件正中点坐标
int y0=this.getHeight()/2;
g.setColor(color); //设置画线颜色
g.drawLine(x0,0,x0,y0*2); //画Y轴
g.drawLine(0,y0,x0*2,y0); //画X轴
int j=40;
while(j<this.getWidth()/3.5) //画若干圈四叶玫瑰线
{
for(int i=0;i<1023;i++) //画一圈四叶玫瑰线的若干点
{
double angle = i*Math.PI/512;
double radius = j*Math.sin(2*angle);
int x =(int) Math.round(radius*Math.cos(angle)*2);
int y =(int) Math.round(radius*Math.sin(angle));
g.fillOval(x0+x,y0+y,1,1); //画直径为1的圆就是一个点
}
j += 20;
}
}
public void componentResized(ComponentEvent e) //改变组件大小时
{
this.repaint(); //重画
}
public void componentMoved(ComponentEvent e) { }
public void componentHidden(ComponentEvent e) { }
public void componentShown(ComponentEvent e) { }
} |
|