Tip: Button 需搭配ActionListener的actionPerformed Event;repaint() 物件是先進入 update() 才進入 paint(),但是Frame預設的update()有自動清理的功能,因此要override update(),如此一來重繪製時才能保留上次的痕跡
import java.awt.*;
import java.awt.event.*;
public class mm extends Frame implements WindowListener, ActionListener{
int sfg = 0,cnt=0;
mm(){
this.setSize(1000,1000);
this.setLocation(300,200);
this.setLayout(null);
/*Button*/
Button bt = new Button("Paint~");
bt.setSize(50, 20);
bt.setLocation(60,60);
bt.addActionListener(this);/*interface*/
this.addWindowListener(this);/*interface*/
this.add(bt);
this.setVisible(true);
bt.setVisible(true);
}
/*Override Frame*/
public void update(Graphics g){paint(g);}
public void paint(Graphics g){
int x=0,y=0,r=200;
if(sfg==1){
Color cr = new Color(fun.Rand(0,255),fun.Rand(0,255),fun.Rand(0,255));
g.setColor(cr);
for(int th=0;th<360;th++)
{
x = (int)(r*Math.cos(th*3.14159/180))+250+cnt;
y = (int)(r*Math.sin(th*3.14159/180))+250;
int r2=5;
g.drawOval(x-r2, y-r2, r*2, r*2);
}
}else if(sfg==2){
g.setColor(new Color(fun.Rand(0,255),fun.Rand(0,255),fun.Rand(0,255)));
for(int th=0;th<360;th++)
{
x = th+90;
y = (int)(-50*Math.sin(th*3.14159/180))+250;
int r2=1;
g.drawOval(x-r2, y-r2, r2*2+1, r2*2+1);
}
}
}
public static void main(String[] args)
{
mm p = new mm();
}
/*Switch*/
@Override
public void actionPerformed(ActionEvent e) {
if(sfg>0)sfg=0;
sfg++;
cnt++;
repaint();
}
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
dispose();
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
}
留言列表