Search code examples
javaswinguser-interfacebackgroundtransparency

Problems with the alpha parameter when setting a background color for JTextFields


I am writing a chat program and I was trying to make it more interesting by adding a background image to the main JPanel (the one on which everything is built). When I try to change the transparency of a JTextField or JTextArea 50% using the code

MainPanel = new JPanel(){

@Override
    public void paintComponent(Graphics g) {
        ImageIcon im = new ImageIcon("background.jpg");
        Image i = im.getImage();

        g.drawImage(i,0,0,this.getSize().width,this.getSize().height,this);
    }
};

...

outputWindow.setBackground(new Color(0,0,0,128));

where 'outputWindow' is a JTextArea added to 'MainPanel', I get a lot of garble once I display some text in the area. Screenshot of the problem

I typed in "hi" and "hello world" in that order, which you can see at the top of the output screen, but is there any way to get rid of the extra garble?


Solution

  • For each Swing component which is partially transparent, be sure you call setOpaque(false);

    https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/