I am confused regarding the display of components in a JPanel.
Suppose if I create a custom JPanel with translucency of 0.8f as follows :-
JPanel pan
Generally, you want to override paintComponent()
not paint()
. This is likely the cause of your transparency issues. Second, you probably want to change the layout. By default panels use FlowLayout. You likely want to use BorderLayout or GridBagLayout or a mix of the two.
1) Then in the output why I get translucent buttons? As JPanel is single layered and I painted the translucent image first when I overrided its paint method and then buttons were added, the buttons must not be translucent as they should come over it.
Actually, you painted the translucent effect OVER the buttons. paint
calls
paintComponent
paintBorder
paintChildren
Then you painted your translucent effect OVER the top of what has already been painted (the children). It will make no difference when you add the components, Swing will paint the component under a number of circumstances, the first been when the component is first realised (made visible on the screen) and in response to changes to the dirty regions (and lots of others)...don't fool your self, you have no control over this...
Think of the paint process as a layering approach. First you paint the background, then you paint the mid ground and then finally, the fore ground, which then you went and splashed over...
public class TestTranslucentControls {
public static void main(String[] args) {
new TestTranslucentControls();
}
public TestTranslucentControls() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage background;
public TestPane() {
setLayout(new GridBagLayout());
try {
background = ImageIO.read(new File("C:/Users/shane/Dropbox/MegaTokyo/poster.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
add(new JButton("1"));
add(new JButton("2"));
add(new JButton("3"));
add(new JButton("4"));
add(new JButton("5"));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.SrcOver.derive(0.25f));
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g2.drawImage(background, x, y, this);
g2.dispose();
}
}
@Override
public Dimension getPreferredSize() {
return background == null ? new Dimension(300, 300) : new Dimension(background.getWidth(), background.getHeight());
}
}
}
I think you may find...
useful ;)