我已经覆盖了JPanels,背景有一个图像可以阻止前景在applet的加载上绘制。 setOpaque(false)工作正常(重新绘制两个面板二十次你[?]),但我需要它不透明有BG颜色,不透明的背景导致重新涂抹自己3次,这抹去了顶部面板:
public class LayeredPanelsTest extends JApplet
{
private Image _image;
@Override
public void init()
{
_image = getImage( getDocumentBase(), "./images/flag.GIF" );
setSize( 450, 450 );
setLayout( new OverlayLayout( getContentPane() ) );
final BottomPanel background = new BottomPanel();
background.setBounds( 10, 10, 400, 400 );
final TopPanel foreGround = new TopPanel();
foreGround.setBounds( 10, 10, 400, 400 );
add( foreGround );
add( background );
}
public class BottomPanel extends JPanel
{
public BottomPanel()
{
setBackground(Color.CYAN);
setLayout( new FlowLayout() );
setOpaque( true );//with false foreground is painted just fine, but they get repainted like 20 times.
}
@Override
public void paintComponent( final Graphics g )
{
super.paintComponent( g );
g.drawImage( _image, 10, 10, this );
System.out.println( "Bottom" );
}
}
public class TopPanel extends JPanel
{
int _mouseX = 10;
public TopPanel()
{
setLayout( new FlowLayout() );
setOpaque( false );
addMouseListener( new MouseAdapter()
{
@Override
public void mousePressed( final MouseEvent evt ) {
_mouseX = evt.getX();
repaint();
}
});
}
@Override
public void paintComponent( final Graphics g )
{
super.paintComponent( g );
g.drawLine( _mouseX, 0, _mouseX, 80);
System.out.println( "Top" );
}
}
}