I was trying to create a transparent button with an image on it . But as I make the button transparent , image also get transparent too . I do not want this to happen . I want only the background of the button to be transparent with no changes in the original image . Please help me with my mistakes.
Here is my code .
CODE
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Image;
import java.awt.GradientPaint;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
class myButton extends JButton
{
String imgUrl,style;
GradientPaint gp = new GradientPaint(100, 300, Color.GRAY, 0, 75, Color.WHITE, true);
public myButton(String txt)
{
super();
imgUrl=txt;
setPreferredSize(new Dimension(50, 25));
setBorderPainted(false);
setFocusPainted(false);
setContentAreaFilled(false);
}
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
int w= getWidth(),h=getHeight();
// fill the clipped area
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
// paint outer border
g2d.setPaint(Color.GRAY);
g2d.drawRect(0, 0, w+30, h-1 );
// paint inner border
g2d.setPaint(Color.WHITE);
g2d.drawRect(1, 1, w+30 , h-3);
// paint right outside border
g2d.setPaint(Color.GRAY);
g2d.drawLine(w - 1, 1, w - 1, h);
// paint right inside border
g2d.setPaint(Color.WHITE);
g2d.drawLine(w - 2, 2, w - 2, h - 1);
//----------adding image -----------
ImageIcon img=new ImageIcon(imgUrl);
Image image = img.getImage();
Composite oldcomp = g2d.getComposite();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f));
g2d.drawImage(image, 15, 5, this);
g2d.setComposite(oldcomp);
super.paintComponent(g);
g2d.dispose();
}
}
here constructor myButton(String txt) can be used instead of JButton(String txt) . In mybutton constructor argument String txt has been used to pass the name of the image file ,its in .png format in my case .
This post has been edited by cybernaut09: 15 Jun, 2008 - 05:26 AM