1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TransparencyExample extends JPanel
{
private static int gap=10, width=60, offset=20,
deltaX=gap+width+offset;
private Rectangle
blueSquare = new Rectangle(gap+offset, gap+offset, width, width),
redSquare = new Rectangle(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) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for(int i=0; i<11; i++) {
drawSquares(g2d, i*0.1F);
g2d.translate(deltaX, 0);
}
}
static public JFrame createFrame( JPanel content, int width, int height )
{
JFrame frame = new JFrame("Title");
frame.setBackground( Color.lightGray );
content.setBackground( Color.lightGray );
frame.setSize( width, height );
frame.setContentPane(content);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent event) {
System.exit(0);
}
});
frame.setVisible(true);
return(frame);
}
public static void main(String[] args)
{
JFrame frame = createFrame(
new TransparencyExample() ,
11*deltaX + 2*gap, deltaX + 3*gap
);
frame.setVisible( true);
}
} |
Partager