Reputation: 153
I have JButton that has an ImageIcon and some text. I want to have transparent background with no borders but also want to have some padding.
Here is what I have tried:
Jbutton button = new JButton();
//Add image to the button
ImageIcon img= new ImageIcon(imgUrl);
button.setIcon(img);
//make button transparent
button.setBackground(new Color(255,255,255,0));
//Remove border
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
//add padding
button.setBorder(BorderFactory.createEmptyBorder(5,10,5,50));
I still see gray border around by border. When I do button.setBorder(null) that gray border line disappears but then I am not able to add padding.
If someone can please guide me on what I am doing wrong. I am very new to swing and have tried different answers but none of them have worked.
Thank you.
Upvotes: 0
Views: 2022
Reputation: 347332
setBackground(new Color(255,255,255,0))
, Swing only supports fully opaque or fully transparent components, controlled via the opaque
property, using a alpha based color can produce undesirable side effectssetMargins
to generate paddingExample...
Original Image...
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Launcher {
public static void main(String[] args) {
new Launcher();
}
public Launcher() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
JButton button = new JButton();
ImageIcon img = new ImageIcon(ImageIO.read(getClass().getResource("Cup.png")));
button.setIcon(img);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
button.setOpaque(true);
button.setMargin(new Insets(10, 10, 10, 10));
JFrame frame = new JFrame();
// Just testing to see there are glitches
frame.setLayout(new GridBagLayout());
frame.add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Launcher.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
I did find that if you used setBorder
, it overrode the margin
values
Upvotes: 1
Reputation: 4517
How you set the margin, to any of swing component deoends on the layoutmanager.
If you are using GridBagLayout, you shall set insets on the GridBagConstraint object to the desired value.
Upvotes: 0