I need to make a JButton with an image icon and regular text. This question is not duplicate of How to make JButton with transparent background and regular text? , as I need to upload an image as icon and make it transparent as well. I tried to use overriden paintComponent() method
@Override
public void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
super.paintComponent(g2);
}
But all it does is paints icon and text both transparent, also button does not refresh properly. Are there any possible workarounds?
UPDATE
The way I am setting the button is the following (item.getImage() returns array of bytes):
setFocusable(true);
setFocusPainted(true);
setVerticalTextPosition(SwingConstants.CENTER);
setHorizontalTextPosition(SwingConstants.CENTER);
if(item.getImage() != null) {
int w = BUTTON_SIZE - 10;
int h = BUTTON_SIZE - 10;
if(menuItem.isShowImageOnly()) {
setIcon(menuItem.getScaledImage(w, h));
}
else {
w = 80;
h = 40;
setIcon(menuItem.getScaledImage(w, h));
}
Just draw the transparency on the Image first
Image im = ...;
java.awt.Graphics2D g2 = (java.awt.Graphics2D) im.getGraphics();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2.drawImage(0,0, im, null);
g2.dispose();
ImageIcon icon = ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.