InsaneCoder
InsaneCoder

Reputation: 8288

How to make JScrollPane Transparent in Java Swing

I have to display a long Text on my screen so I wrappedJTextArea inside JScrollPane.Now I want to make this combo-container to be transparent such that only text is seen which looks like a JLabel is written on JFrame.

So I made them transparent using the following code

class Body extends JTextArea
{
    Body(String text)
    {
        super(text);
        setOpaque(false);
        setSize(400,200);
        setWrapStyleWord(true);
        setLineWrap(true);
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(new Color(12,25,55,0));
        g.fillRect(0,0,this.getWidth(),this.getHeight());
    }
}

class CustomScrollPane extends JScrollPane
{
    CustomScrollPane(JTextArea textArea)
    {
        super(textArea);
        setOpaque(false);
        setSize(400,200);
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(new Color(220,10,10,0));
        g.fillRect(0,0,this.getWidth(),this.getHeight());
    }
}

But I am getting opaque container.

When I directly added the JTextArea to JFrame it is transparent ,but adding it through JScrollPane creates problem.

Any Help?

Upvotes: 0

Views: 2697

Answers (1)

Sage
Sage

Reputation: 15418

  1. you can set the JScrollPane view port's opaque to false by asking the JScrollPane instance to return it's view port:

     jScrollPane1.getViewport().setOpaque(false);
    
  2. In your code why you are setting size using setSize(Dimension) method. Don't tell me you working with NullLayout. Learn to use Layout Mangers. They will make you happy.

Edit:

Ok, use an extension of JViewPort, you can paint anything inside if necessary:

class MyViewPort extends JViewport
{

    public MyViewPort() {
        setOpaque(false);
    }

}

Then set an instance of MyViewPort as your JScrollPane's view port invoking:

setViewport(new MyViewPort())

Upvotes: 2

Related Questions