import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TransparentPanel extends JPanel implements ActionListener {
private final JFrame owner;
TransparentPanel(final JFrame owner) {
this.owner = owner;
setOpaque(false);
setBackground(new Color(100, 100, 100, 200));
JButton btClose = new JButton("Close");
add(btClose);
setSize(200, 150);
JLayeredPane layeredPane = owner.getLayeredPane();
layeredPane.add(this, JLayeredPane.POPUP_LAYER);
setVisible(false);
btClose.addActionListener(this);
owner.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
setVisible(isVisible());
}
});
}
@Override
protected void paintComponent(final Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
public void actionPerformed(final ActionEvent e) {
setVisible(false);
}
@Override
public void setVisible(final boolean visible) {
super.setVisible(visible);
if (isVisible()) {
int wO = owner.getWidth();
int hO = owner.getHeight() - 30;
setLocation((wO - getWidth()) / 2, (hO - getHeight()) / 2);
}
}
public static void main(final String[] args) {
Runnable gui = new Runnable() {
public void run() {
JFrame frame = new JFrame("Transparent Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
JButton btShow = new JButton("Show transparent panel");
final TransparentPanel transparentPanel = new TransparentPanel(frame);
btShow.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent evt) {
transparentPanel.setVisible(true);
}
});
frame.add(btShow, BorderLayout.PAGE_START);
frame.add(new JColorChooser(), BorderLayout.CENTER);
frame.setVisible(true);
}
};
//GUI must start on EventDispatchThread:
SwingUtilities.invokeLater(gui);
}
}