java 2d 绘制滚动的虚线(蚂蚁线)

package test; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.GeneralPath; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class ShowMovedDottedLine extends JPanel implements ActionListener{ @Override public void paint(Graphics g) { Color c = getBackground(); Graphics2D g2 = (Graphics2D)g; g2.setColor(c); g2.fillRect(0, 0, this.getWidth(),this.getHeight()); g2.setColor(Color.RED); g2.setStroke(bs[(index++)%6]); g2.draw(path); } private static final long serialVersionUID = 1L; Timer timer ; GeneralPath path; final BasicStroke[] bs = new BasicStroke[6]; int index = 0; public ShowMovedDottedLine(){ timer=new Timer(50,this); path = new GeneralPath(); path.moveTo(50, 50); path.lineTo(200, 200); float[] dash = new float[]{5,5}; for (int i = 0; i < 6; i++) { bs[i] = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, i); } timer.start(); } public void actionPerformed(ActionEvent e) { repaint(); } public static void main(String[] args) { JFrame frame=new JFrame(); frame.setSize(800,800); ShowMovedDottedLine show = new ShowMovedDottedLine(); frame.getContentPane().add(show,BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

 

 

这个问题困扰了很久,在网上提问也没有找到答案,最后是在http://1632004.blog.163.com/blog/static/29991497200771805319786/

这个帖子的帮助下完成的,上面是例子代码

你可能感兴趣的:(java,timer,String,Class,Path,float)