下面是结合“被动”Swing 组件和主动动画的一些示例:
public static void main ( String[] args )
{
JFrame frame = new JFrame ();
JPanel view = new JPanel ( null );
view.setPreferredSize ( new Dimension ( 500, 500 ) );
frame.add ( view );
JButton button1 = new JButton ( "Button 1" );
button1.setBounds ( 10, 10, 100, 40 );
button1.setOpaque ( false );
view.add ( button1 );
Animator animator = new Animator ();
animator.setBounds ( 0, 0, 500, 500 );
view.add ( animator );
JButton button2 = new JButton ( "Button 2" );
button2.setBounds ( 390, 450, 100, 40 );
button2.setOpaque ( false );
view.add ( button2 );
frame.setResizable ( false );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
public static class Animator extends JComponent
{
private float angle = 0;
public Animator ()
{
super ();
setOpaque ( false );
new Timer ( 1000 / 24, new ActionListener ()
{
public void actionPerformed ( ActionEvent e )
{
angle += 0.2f;
if ( angle > 360 )
{
angle = 0;
}
repaint ();
}
} ).start ();
addMouseListener ( new MouseAdapter ()
{
//
} );
}
protected void paintComponent ( Graphics g )
{
super.paintComponent ( g );
Graphics2D g2d = ( Graphics2D ) g;
g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON );
GeneralPath shape = getShape ();
g2d.setPaint ( Color.BLACK );
g2d.fill ( shape );
}
public boolean contains ( int x, int y )
{
return getShape ().contains ( x, y );
}
private GeneralPath getShape ()
{
GeneralPath gp = new GeneralPath ( GeneralPath.WIND_EVEN_ODD );
gp.append ( new Rectangle2D.Double ( -250, 150, 1000, 200 ), false );
AffineTransform at = new AffineTransform ();
at.rotate ( angle * Math.PI / 90, 250, 250 );
gp.transform ( at );
return gp;
}
}
正如您所看到的,黑色旋转区域不仅覆盖了右下角的按钮,而且还阻止了被条纹按钮覆盖的部分上的鼠标事件。这是因为重写了 Animator 的 contains() 方法:
public boolean contains ( int x, int y )
{
return getShape ().contains ( x, y );
}
默认情况下,组件会在父级的整个边界上捕获鼠标事件,但是通过更改此方法,您可以按照自己喜欢的方式进行操作。
还可以进行很多优化,例如在每次重绘后将形状保存到某个变量,并在检查“包含”值时返回它。
无论如何,希望这至少对您的问题有所帮助...