views:

872

answers:

3

Hi,

I need to know if a JPanel`s bacground can be set to Transparent?

My frame is has two Jpanels Image Panel and Feature Panel, Feature Panel is overlapping Image Panel, the Image Panel is working as a background and it is loading image from a remote Url, now I want to draw shaps on Feature Panel , but now Image Panel cannot be seen due to Feature Panel's background color. I need to make Feature Panel background transparent while still drawing its shapes and i want Image Panel to be visible since it is doing tiling and cache function of images. I need to seperate the image drawing and shape drawing thats why I`m using two jPanels! is there anyway the overlapping Jpanel have a transparent background?

thanks

+1  A: 

Calling setOpaque(false) on the upper JPanel should work.

From your comment, it sounds like Swing painting may be broken somewhere -

First - you probably wanted to override paintComponent() rather than paint() in whatever component you have paint() overridden in.

Second - when you do override paintComponent(), you'll first want to call super.paintComponent() first to do all the default Swing painting stuff (of which honoring setOpaque() is one).

Example -

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class TwoPanels {
    public static void main(String[] args) {

        JPanel p = new JPanel();
        // setting layout to null so we can make panels overlap
        p.setLayout(null);

        CirclePanel topPanel = new CirclePanel();
        // drawing should be in blue
        topPanel.setForeground(Color.blue);
        // background should be black, except it's not opaque, so 
        // background will not be drawn
        topPanel.setBackground(Color.black);
        // set opaque to false - background not drawn
        topPanel.setOpaque(false);
        topPanel.setBounds(50, 50, 100, 100);
        // add topPanel - components paint in order added, 
        // so add topPanel first
        p.add(topPanel);

        CirclePanel bottomPanel = new CirclePanel();
        // drawing in green
        bottomPanel.setForeground(Color.green);
        // background in cyan
        bottomPanel.setBackground(Color.cyan);
        // and it will show this time, because opaque is true
        bottomPanel.setOpaque(true);
        bottomPanel.setBounds(30, 30, 100, 100);
        // add bottomPanel last...
        p.add(bottomPanel);

        // frame handling code...
        JFrame f = new JFrame("Two Panels");
        f.setContentPane(p);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300, 300);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    // Panel with a circle drawn on it.
    private static class CirclePanel extends JPanel {

        // This is Swing, so override paint*Component* - not paint
        protected void paintComponent(Graphics g) {
            // call super.paintComponent to get default Swing 
            // painting behavior (opaque honored, etc.)
            super.paintComponent(g);
            int x = 10;
            int y = 10;
            int width = getWidth() - 20;
            int height = getHeight() - 20;
            g.drawArc(x, y, width, height, 0, 360);
        }
    }
}
Nate
I did , but it did not work,should I call this function in the constructor or in the paint() method?
Imran
@Imran - In the constructor or in the paint() method of what? The panel itself? see updated answer...
Nate
Alright thanks Nate, that worked. before calling super.paint() I set Opaque to false and then before drawing my shape I set Opaque to true. thanks buddy
Imran
You shouldn't have to set it on and off... basically all `setOpaque()` handles is whether the "background" should be painted or not - you can just call it on the panel right after you create it and it will stay set. If you have an overridden `paintComponent()` on that panel, you can paint on the component (and be sure to call super.paintComponent() so default Swing painting can occur) and anything you draw will be treated as "foreground" and will show up without calling `setOpaque(true)`.
Nate
Ok I think i spoke too soon, now the problem is upside down. The contents of the overlapping Jpanel are erased when the Jpanel which is below redraws. Its some kind of a round robin. I draw the overlapping Jpanel without background, but when as soon as the overlapped jpanel redraws the overlapping jpanel looses its contents, hmmmm..now what.
Imran
Post some code representative of what you're doing... I'll post a short example, too.
Nate
hey thanks for your response. I got it working but the overlapping JPanel is expereincing a lot of Flickering. The overlapped panel does a fade in on new image load. Both panels are being painted through seperate threads. Now the overlapped thread draws xml response. Xml response loads and draws before the image is loaded in the overlapped Jpanel. During the fadeIn function of overlapped JPanel, the already drawn overlapping Japenl starts flickering and looks very ugly. just for your info. I`m trying to write a rich client for a web-mapping application that shows satellite image and features
Imran
The threading part - are you using SwingUtilities.invokeLater(), SwingWorker, or anything similar to handle updating only in the EDT? How often are you updating - the "flickery" description sounds like you're trying to update the component faster than it can really repaint, so it's repainting "as available" and not at a set rate. Or it could be many other things... threading issues, doing too much processing on the EDT, etc.
Nate
+1  A: 

Alternatively, consider The Glass Pane, discussed in the article How to Use Root Panes. You could draw your "Feature" content in the glass pane's paintComponent() method.

Addendum: Working with the GlassPaneDemo, I added an image:

/* Set up the content pane, where the "main GUI" lives. */
frame.add(changeButton, BorderLayout.SOUTH);
frame.add(new JLabel(new ImageIcon("img.jpg")), BorderLayout.CENTER);

and altered the glass pane's paintComponent() method:

protected void paintComponent(Graphics g) {
    if (point != null) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, 0.3f));
        g2d.setColor(Color.yellow);
        g2d.fillOval(point.x, point.y, 120, 60);
    }
}

alt text

trashgod
Using a glasspane won't work (correctly) without setOpaque() (as described in my post) working.
Nate
What doesn't work? I'm not sure how `setOpaque()` applies; I thought you wanted translucent.
trashgod
+1  A: 
 public void paintComponent (Graphics g)
    { 
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.0f)); // draw transparent background
     super.paintComponent(g);
    ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f)); // turn on opacity
    g.setColor(Color.RED);
    g.fillRect(20, 20, 500, 300);
     } 

I have tried to do it this way, but it is very flickery

Imran