这是一个从零开始完全绘制和动画的移动虚线的小例子:
private static int speed = 5;
public static void main ( String[] args )
{
JFrame frame = new JFrame ();
frame.setLayout ( new BorderLayout () );
frame.add ( new JComponent ()
{
private int diff = 0;
{
final Timer timer = new Timer ( 1000 / ( 10 * speed ), null );
timer.addActionListener ( new ActionListener ()
{
public void actionPerformed ( ActionEvent e )
{
if ( diff < 20 )
{
diff++;
}
else
{
diff = 0;
}
repaint ();
timer.setDelay ( 1000 / ( 10 * speed ) );
}
} );
timer.start ();
}
protected void paintComponent ( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON );
g2d.setStroke (
new BasicStroke ( 5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f,
new float[]{ 10f, 10f }, diff ) );
g2d.setPaint ( Color.BLACK );
g2d.drawLine ( 0, getHeight () / 2, getWidth (), getHeight () / 2 );
}
} );
frame.add ( new JSlider ( JSlider.HORIZONTAL, 1, 10, speed )
{
{
addChangeListener ( new ChangeListener ()
{
public void stateChanged ( ChangeEvent e )
{
speed = getValue ();
}
} );
}
}, BorderLayout.SOUTH );
frame.setSize ( 500, 500 );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
基本上,对于动画,您需要绘制大部分想要制作动画的东西。在您的情况下,如果它是用虚线连接的两个对象 - 您可以使用绘制该连接的容器并仅放置在其上的简单 Swing 组件。所以它会检测它们的边界并绘制连接线......