How to make jTextArea transparent background

I want to make the jTextArea transparent background. I'm trying to setBackground (new color (0,0,0,0)); JTextField works, jTextArea doesn't work.

like this code.

// Not working.. Just remains gray.
    jScrollPane1.setOpaque(false);
    jScrollPane1.setBackground(new Color(0,0,0,0));
    jTextArea1.setOpaque(false);
    jTextArea1.setBackground(new Color(0,0,0,0));

    // Working.. As it wants to be transparent.
    jTextField1.setOpaque(false);
    jTextField1.setBackground(new Color(0,0,0,0));

      

enter image description here

How can I transparent background jTextArea?

Thanks and regards.

+3


source to share


3 answers


A JScrollPane

is a composite component, it controls / contains a JViewport

which is a component that executes drawings. See API:

A common operation to do is to set the background color to be used if the main view of the viewport is smaller than the viewport or not opaque. This can be done by setting the background color of the viewport through scrollPane.getViewport (). setBackground (). The reason for setting the color of the viewport and not the scrollpane is that by default the JViewport is opaque, which, among other things, means that it will completely fill its background using the background color. So when the JScrollPane draws the background, the viewport will usually draw over it.



Thus, you must change the opaque and color properties JViewport

. You can access it with jScrollPane1.getViewport()

.

+3


source


Here's an example: 50% transparent

JTextArea textArea = new JTextArea();
textArea.setOpaque(false);

JScrollPane scrollPane = new JScrollPane(textArea) {
    @Override
    protected void paintComponent(Graphics g) {
        try {
            Composite composite = ((Graphics2D)g).getComposite();

            ((Graphics2D)g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
            g.setColor(getBackground());
            g.fillRect(0, 0, getWidth(), getHeight());

            ((Graphics2D)g).setComposite(composite);
            paintChildren(g);
        }
        catch(IndexOutOfBoundsException e) {
            super.paintComponent(g);
        }
    }       
};

scrollPane.getViewport().setOpaque(false);
scrollPane.setOpaque(false);

      



edit sorry for the mistake. This is a job.

0


source


The following worked for me.

JTextArea textArea = new JTextArea();
textArea.setOpaque(false);
textArea.setBackground(new Color(red, green, blue, alpha));

JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.getViewport().setOpaque(false);
scrollPane.setOpaque(false);

      

0


source







All Articles