JButton透明背景设置
方法1:JButton b1=new JButton();
b1.setOpaque(false);
b1.setColor(new Color(2,2,2)); //此颜色值随便设置,只起占位作用,但是必须加上此句,否则不会出现透明背景效果。
b1..setIcon(new ImageIcon("bin/filechooser/image/rec.gif"));
方法2:JButton b2=new JButton();
b2.setContentAreaFilled(false); //只须加上此句
b2.setIcon(new ImageIcon("bin/filechooser/image/rec.gif"));
END
package swing.component;
/*
* 此程序所用的图片必须是背景透明的
*/
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* 这是面板绘制图像的程序
* @author MyTest
*
*/
public class TransparencyButton extends JFrame {
public static void main(String[] args) {
TransparencyButton frame = new TransparencyButton();
frame.setBounds(322, 26, 500, 160);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TransparencyButton() {
setTitle("ImageTest");
ImagePanel panel = new ImagePanel();
add(panel);
}
}
class ImagePanel extends JPanel {
private Image image = null;
private JButton b1 = null;
public ImagePanel() {
try {
image = ImageIO.read(new File("swing/component/img/aaa.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Color c = new Color(0,0,255);//背影颜色随便设任意值,只起占位作用。
b1 = new JButton();
ImageIcon icon = new ImageIcon("swing/component/img/r6.gif");//此图标必须是背影透明的
b1.setOpaque(false);//设置透明背影
b1.setBackground(c);//必须设置否则不会出现透明背影
b1.setIcon(icon);
b1.getIcon();
add(b1);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image == null)return;
g.drawImage(image, 0, 0, null);
}
}