Draw ten rectangles with different levels of transparency in Java
Description
The following code shows how to draw ten rectangles with different levels of transparency.
Example
// w w w . jav a2 s . c o m
import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
for (int i = 1; i <= 10; i++) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, i * 0.1f));
g2d.fillRect(50 * i, 20, 50, 50);
}
}
}
public class Main {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 450, 450);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
The code above generates the following result.