《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: opaquetest.java
import javax.swing.*;
import java.awt.*;
public class OpaqueTest extends JApplet {
public void init() {
Container contentPane = getContentPane();
RainPanel rainPanel = new RainPanel();
ColoredPanel opaque = new ColoredPanel(),
transparent = new ColoredPanel();
// JComponents are opaque by default, so the opaque
// property only needs to be set for transparent
transparent.setOpaque(false);
rainPanel.add(opaque);
rainPanel.add(transparent);
contentPane.add(rainPanel, BorderLayout.CENTER);
System.out.println(opaque.isOpaque());
System.out.println(transparent.isOpaque());
}
}
class RainPanel extends JPanel {
ImageIcon rain = new ImageIcon("rain.gif");
private int rainw = rain.getIconWidth();
private int rainh = rain.getIconHeight();
public void paintComponent(Graphics g) {
Dimension size = getSize();
for(int row=0; row < size.height; row += rainh)
for(int col=0; col < size.width; col += rainw)
rain.paintIcon(this,g,col,row);
}
}
class ColoredPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = getSize();
g.setColor(Color.black);
g.drawRect(0,0,size.width-1,size.height-1);
g.setColor(Color.red);
g.fillRect(size.width/2-25,size.height/2-25,50,50);
}
public Dimension getPreferredSize() {
return new Dimension(100,100);
}
}