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