Reputation: 169
I want to make a transparent background jTextArea. I try to setBackground(new color(0,0,0,0)); jTextField is Working, jTextArea didn't working.
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));
How can I jTextArea transparent background?
Thanks & Regards.
Upvotes: 7
Views: 19933
Reputation: 263
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);
Upvotes: 5
Reputation: 2849
This is example include 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 bug. This is work.
Upvotes: 0
Reputation: 36401
A JScrollPane
is a composed component, it controls/contains a JViewport
which is the component that does the drawings. See API:
A common operation to want to do is to set the background color that will be used if the main viewport view is smaller than the viewport, or is not opaque. This can be accomplished by setting the background color of the viewport, via scrollPane.getViewport().setBackground(). The reason for setting the color of the viewport and not the scrollpane is that by default JViewport is opaque which, among other things, means it will completely fill in its background using its background color. Therefore when JScrollPane draws its background the viewport will usually draw over it.
So you should change the opaque and color properties of the JViewport
as well. You can access it with jScrollPane1.getViewport()
.
Upvotes: 5