RE:color transparente some Test
import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
/**
* Tool class.
*/
public class PaintTest extends JFrame {
private ImagePane imagePane;
public PaintTest() {
setTitle("Transparency test");
Container contentPane = getContentPane();
// Your image here!!!
imagePane = new ImagePane(new File("c:\\test.jpg"));
contentPane.add(imagePane);
imagePane.add(new JButton("Test"), BorderLayout.SOUTH);
imagePane.add(new TransparentButton(), BorderLayout.NORTH);
}
public static void main(String[] args) {
final JFrame frame = new PaintTest();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// some small hack try too comment next line //
// bad redraw :(
frame.addMouseMotionListener(new PaintTest().new MyMouseMotionListener());
frame.pack();
frame.setVisible(true);
}
class MyMouseMotionListener extends MouseMotionAdapter {
public void mouseMoved(MouseEvent e) {
e.getComponent().repaint();
}
}
}
/**
* Just a panel with the image inside
*/
class ImagePane extends JPanel {
private File imageFile;
private BufferedImage image;
ImagePane(File imageFile) {
// Image path
this.imageFile = imageFile;
try {
image = ImageIO.read(imageFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
public boolean isOpaque() {
return true;
}
protected void paintComponent(Graphics g) {
// opaque, no need super.paintComponent();
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, null, 0, 0);
}
}
/**
* Small transparent button
*/
class TransparentButton extends JButton {
public TransparentButton() {
super();
setText("Transparent test");
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
// Main part try too play with rule and alpha
int rule = AlphaComposite.SRC_OVER;
float alpha = 0.5f;
g2.setComposite(AlphaComposite.getInstance(rule, alpha)); //!!!
super.paintComponent(g2);
}
}