I'm not sure if this is possible, but is there a way to safely allow popups to be translucent even when the parent container is also translucent?
If not, what would be wise alternative to use or extend instead of JPopupMenu
?
Note: Translucent refers to a component not 'having a background', similar to the effect of setOpaque(false);
. Thanks.
From a forum answer by user camickr in 2009:
I don't know if transparency painting has changed in 1.6.0_10. Prior to that I believe transparency can only be achieved in lightweight components (ie. Swing does all the painting). JFrame, JWindow and JDialog are not lightweight because they use OS components.
In the case of a popup, it is lightweight when entirely contained within its parent frame. But a lightweight popup can not be painted outside the bounds of the frame so a JWindow (I believe) is used as the popup, which can't be transparent.
SSCCE: Showing translucent JWindow over the top of translucent JFrame
import com.sun.awt.AWTUtilities;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class OpaqueWindowSSCCE {
private int countdown = 5;
public static void main(String[] args) {
new OpaqueWindowSSCCE();
}
public OpaqueWindowSSCCE() {
final JFrame frame = new JFrame("OpaqueWindowSSCCE");
final JWindow window = new JWindow();
new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(--countdown == 0){
frame.dispose();
window.dispose();
System.exit(0);
} else {
frame.repaint();
}
}
}).start();
frame.setContentPane(new JPanel() {
@Override
public void paintComponent(Graphics paramGraphics) {
super.paintComponent(paramGraphics);
Graphics2D g = (Graphics2D) paramGraphics.create();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(50, 50, 50));
g.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
g.setColor(new Color(180, 180, 180));
g.drawString("Closing in " + countdown + " seconds", 20, 25);
}
});
window.setContentPane(new JPanel() {
@Override
public void paintComponent(Graphics paramGraphics) {
super.paintComponent(paramGraphics);
Graphics2D g = (Graphics2D) paramGraphics.create();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(180, 180, 180));
g.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
}
});
frame.setUndecorated(true);
((JComponent) frame.getContentPane()).setOpaque(false);
((JComponent) window.getContentPane()).setOpaque(false);
AWTUtilities.setWindowOpaque(frame, false);
AWTUtilities.setWindowOpaque(window, false);
window.setAlwaysOnTop(true);
frame.setBounds(200,200,500,500);
window.setBounds(600,600,200,200);
frame.setVisible(true);
window.setVisible(true);
}
}
JWindow
using this funciton setOpacity(). – Purree