I have a large java program with a JFrame
window where I need to make a transparent background, but this is only possible without my scroll pane (see the following test program and picture):
//TransparentWindow.java
import java.awt.*;
import javax.swing.*;
public class TransparentWindow extends JFrame
{
JMenuBar menuBar;
TransparentCanvas canvas;
JComponent pane;
JScrollPane scrollPane;
public TransparentWindow()
{
setBackground(new Color(0,0,0,0));
setSize(new Dimension(500,500));
setLocationRelativeTo(null); //set location at the center
setTitle("Transparency");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu help = new JMenu("Help");
menuBar.add(help);
canvas = new TransparentCanvas();
pane = (JComponent)this.getContentPane();
pane.add(canvas);
//scrollPane = new JScrollPane(canvas);
//pane.add(scrollPane, BorderLayout.CENTER);
}
public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
TransparentWindow transparentWindow = new TransparentWindow();
transparentWindow.setVisible(true);
}
class TransparentCanvas extends JComponent
{
public TransparentCanvas()
{
super();
setPreferredSize(new Dimension(500,500));
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)g;
g2D.setColor(new Color(240, 240, 240, 128));
g2D.fillRect(0, 0, getWidth(), getHeight());
g2D.setColor(Color.blue);
g2D.fillOval(200, 150, 100, 100);
g2D.dispose();
}
}
}
Transparent window
With the JScrollPane
(by un-commenting the two lines at the end of the constructor above) you get opaque colors (see the following picture):
Opaque window
And calling setUndecorated(true)
does not make it work either.
(By the way, I need to use Java 7, because of some other application.)
Please help. Thanks in advance for your time!