这是千里的一个例子,如果Clock继承自JFrame ,屏幕就会闪;如果像下面这个写,继承JPanel的话,就不会了.
这是为什么
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
public class Clock extends JPanel implements Runnable
{
private JTextField jl;
private JPanel jp;
public Clock()
{
Thread c=new Thread(this);
c.start();
jp=new JPanel();
jl=new JTextField();
jl.setEditable(false);
jl.setHorizontalAlignment(jl.CENTER);
this.setLayout(new BorderLayout());
this.add(jp,BorderLayout.CENTER);
this.add(jl,BorderLayout.SOUTH);
}
public void run()
{
while(true)
{
this.repaint();
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public void paint(Graphics g)
{
super.paint(g);
Calendar cal=Calendar.getInstance();
DateFormat format=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG,this.getLocale());
jl.setText(format.format(cal.getTime()));
int min=Math.min(this.getSize().width,this.getSize().height);
int radix=(int)(min*0.8);
int kedu=(int)(radix*0.48);
int sl=(int)(radix*0.4);
int ml=(int)(sl*0.8);
int hl=(int)(ml*0.8);
int xo=this.getSize().width/2;
int yo=this.getSize().height/2;
for(int i=0;i<60;i++)
{
if(i%5==0)
{
g.drawLine((int)(kedu*0.92*(Math.sin(i*Math.PI/30))+xo),
(int)(yo-(kedu*0.92*(Math.cos(i*Math.PI/30)))),
(int)(xo+(radix/2)*(Math.sin(i*Math.PI/30))),
(int)(yo-(radix/2*(Math.cos(i*Math.PI/30)))));
if(i==0)
g.drawString(""+12,(int)(kedu*0.92*(Math.sin(i*Math.PI/30))+xo),
(int)(yo-(kedu*0.92*(Math.cos(i*Math.PI/30)))));
else
g.drawString(""+i/5,(int)(kedu*0.92*(Math.sin(i*Math.PI/30))+xo),
(int)(yo-(kedu*0.92*(Math.cos(i*Math.PI/30)))));
}
g.drawLine((int)(kedu*(Math.sin(i*Math.PI/30))+xo),
(int)(yo-(kedu*(Math.cos(i*Math.PI/30)))),
(int)(xo+(radix/2)*(Math.sin(i*Math.PI/30))),
(int)(yo-(radix/2*(Math.cos(i*Math.PI/30)))));
}
g.drawOval((this.getSize().width-radix)/2,(this.getSize().height-radix)/2,radix,radix);
Graphics2D gg=(Graphics2D)g;
gg.setColor(Color.MAGENTA);
gg.setStroke(new BasicStroke(4.5f));
gg.drawLine(xo,yo,xo+(int)(hl*Math.sin((cal.get(Calendar.MINUTE)/60.0+cal.get(Calendar.HOUR))*
Math.PI/6)),yo-(int)((hl*Math.cos((cal.get(Calendar.MINUTE)/60.0+cal.get(Calendar.HOUR))*
Math.PI/6))));
gg.setColor(Color.BLUE);
gg.setStroke(new BasicStroke(2.7f));
gg.drawLine(xo,yo,xo+(int)(ml*Math.sin(cal.get(Calendar.MINUTE)*Math.PI/30)),
yo-(int)(ml*Math.cos(cal.get(Calendar.MINUTE)*Math.PI/30)));
gg.setStroke(new BasicStroke(1.0f));
gg.setColor(Color.RED);
gg.drawLine(xo,yo,xo+(int)(sl*Math.sin(cal.get(Calendar.SECOND)*Math.PI/30)),
yo-(int)(sl*Math.cos(cal.get(Calendar.SECOND)*Math.PI/30)));
}
public static void main(String args[])
{
Clock clock=new Clock();
JFrame jf=new JFrame();
jf.add(clock,BorderLayout.CENTER);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400,400);
//clock.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//clock.setSize(400,400);
//clock.setVisible(true);
}
}