import com.sun.java.swing.*; import java.awt.*; import java.awt.geom.*; public class Transparencies extends JPanel { private static double gap=10, width=60, offset=20, deltaX=gap+width+offset; private Rectangle2D.Double blueSquare = new Rectangle2D.Double(gap+offset, gap+offset, width, width), redSquare = new Rectangle2D.Double(gap, gap, width, width); private AlphaComposite makeComposite(float alpha) { int type = AlphaComposite.SRC_OVER; return(AlphaComposite.getInstance(type, alpha)); } private void drawSquares(Graphics2D g2d, float alpha) { Composite originalComposite = g2d.getComposite(); g2d.setPaint(Color.blue); g2d.fill(blueSquare); g2d.setComposite(makeComposite(alpha)); g2d.setPaint(Color.red); g2d.fill(redSquare); g2d.setComposite(originalComposite); } public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.clearRect(0, 0, getSize().width, getSize().height); for(int i=0; i<11; i++) { drawSquares(g2d, i*0.1f); g2d.translate(deltaX, 0); } } public static void main(String[] args) { String title = "Transparency test: alpha of " + "the red square ranges from " + "0.0 at the left to 1.0 at " + "the right."; WindowUtil.openInJFrame(new Transparencies(), (int)(11*deltaX + 2*gap), (int)(deltaX + 3*gap), title, Color.lightGray); } }