Making a JPanel transparent

In the application I am writing I want to allow for some popups on my interface. I am using a JLayeredPane, with two JPanels. The main JPanel, on the default layer, holds all the main components. A second JPanel, at the popup layer, will hold any components which should "pop up".
The layered pane is using a border layout, with both JPanels in the Center.
Unfortunately the bottom panel cannot be seen. It is covered by the top panel, even after I called setOpague(false) on the top panel.
Am I taking the wrong approach? Or is it just not possible to make a JPanel transparent?

It should work.I have fiddled around, but have been unable to get this to work. It seems obvious that I'm doing something wrong. :( Below is an example which mimicks my real code, and hopefully is simple enough.
I appreciate any help you can provide.
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class MyPanel extends JPanel
     public MyPanel()
          setLayout(new BorderLayout());
          add(createLayeredPane(), BorderLayout.CENTER);
     private JLayeredPane createLayeredPane()
          JPanel mainPanel = createMainPanel();
          JPanel popupPanel = createPopupPanel();
          JLayeredPane pane = new JLayeredPane();
          pane.setLayout(new BorderLayout());
          pane.add(mainPanel, BorderLayout.CENTER);
          pane.add(popupPanel, BorderLayout.CENTER);
          pane.setLayer(mainPanel, JLayeredPane.DEFAULT_LAYER.intValue());
          pane.setLayer(popupPanel, JLayeredPane.POPUP_LAYER.intValue());
          return pane;
     private JPanel createMainPanel()
          JList list = new JList(new Object[]{"One","Two","Three"});
          JButton button = new JButton("Do Nothing");
          JPanel panel = new JPanel();
          panel.setLayout(new BorderLayout());
          panel.add(new JScrollPane(list), BorderLayout.CENTER);
          panel.add(button, BorderLayout.SOUTH);
          return panel;
     private JPanel createPopupPanel()
          JLabel label = new JLabel("Hello world!");
          label.setOpaque(false);
          JPanel panel = new JPanel();
          panel.setOpaque(false);
          panel.add(label);
          return panel;
     public static void main(String[] args)
          MyPanel panel = new MyPanel();
          JFrame mainFrame = new JFrame("Testing");
          mainFrame.setContentPane(panel);
          mainFrame.pack();
          mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          mainFrame.show();
}

Similar Messages

  • How to make a JPanel transparent? Not able to do it with setOpaque(false)

    Hi all,
    I am writing a code to play a video and then draw some lines on the video. For that first I am playing the video on a visual component and I am trying to overlap a JPanel for drawing the lines. I am able to overlap the JPanel but I am not able to make it transparent. So I am able to draw lines but not able to see the video. So, I want to make the JPanel transparent so that I can see the video also... I am posting my code below
    import javax.media.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.lang.Math;
    import javax.media.control.FramePositioningControl;
    import javax.media.protocol.*;
    import javax.swing.*;
    class MPEGPlayer2 extends JFrame implements ActionListener,ControllerListener,ItemListener
         Player player;
         Component vc, cc;
         boolean first = true, loop = false;
         String currentDirectory;
         int mediatime;
         BufferedWriter out;
         FileWriter fos;
         String filename = "";
         Object waitSync = new Object();
         boolean stateTransitionOK = true;
         JButton bn = new JButton("DrawLine");
         MPEGPlayer2 (String title)
              super (title);
              addWindowListener(new WindowAdapter ()
                   public void windowClosing (WindowEvent e)
                            dispose ();
                            public void windowClosed (WindowEvent e)
                         if (player != null)
                         player.close ();
                         System.exit (0);
              Menu m = new Menu ("File");
              MenuItem mi = new MenuItem ("Open...");
              mi.addActionListener (this);
              m.add (mi);
              m.addSeparator ();
              CheckboxMenuItem cbmi = new CheckboxMenuItem ("Loop", false);
              cbmi.addItemListener (this);
              m.add (cbmi);
              m.addSeparator ();
              mi = new MenuItem ("Exit");
              mi.addActionListener (this);
              m.add (mi);
              MenuBar mb = new MenuBar ();
              mb.add (m);
              setMenuBar (mb);
              setSize (500, 500);
              setVisible (true);
         public void actionPerformed (ActionEvent ae)
                        FileDialog fd = new FileDialog (this, "Open File",FileDialog.LOAD);
                        fd.setDirectory (currentDirectory);
                        fd.show ();
                        if (fd.getFile () == null)
                        return;
                        currentDirectory = fd.getDirectory ();
                        try
                             player = Manager.createPlayer (new MediaLocator("file:" +fd.getDirectory () +fd.getFile ()));
                             filename = fd.getFile();
                        catch (Exception exe)
                             System.out.println(exe);
                        if (player == null)
                             System.out.println ("Trouble creating a player.");
                             return;
                        setTitle (fd.getFile ());
                        player.addControllerListener (this);
                        player.prefetch ();
         }// end of action performed
         public void controllerUpdate (ControllerEvent e)
              if (e instanceof EndOfMediaEvent)
                   if (loop)
                        player.setMediaTime (new Time (0));
                        player.start ();
                   return;
              if (e instanceof PrefetchCompleteEvent)
                   player.start ();
                   return;
              if (e instanceof RealizeCompleteEvent)
                   vc = player.getVisualComponent ();
                   if (vc != null)
                        add (vc);
                   cc = player.getControlPanelComponent ();
                   if (cc != null)
                        add (cc, BorderLayout.SOUTH);
                   add(new MyPanel());
                   pack ();
         public void itemStateChanged(ItemEvent ee)
         public static void main (String [] args)
              MPEGPlayer2 mp = new MPEGPlayer2 ("Media Player 2.0");
              System.out.println("111111");
    class MyPanel extends JPanel
         int i=0,j;
         public int xc[]= new int[100];
         public int yc[]= new int[100];
         int a,b,c,d;
         public MyPanel()
              setOpaque(false);
              setBorder(BorderFactory.createLineBorder(Color.black));
              JButton bn = new JButton("DrawLine");
              this.add(bn);
              bn.addActionListener(actionListener);
              setBackground(Color.CYAN);
              addMouseListener(new MouseAdapter()
                             public void mouseClicked(MouseEvent e)
                   saveCoordinates(e.getX(),e.getY());
         ActionListener actionListener = new ActionListener()
              public void actionPerformed(ActionEvent aae)
                        repaint();
         public void saveCoordinates(int x, int y)
                    System.out.println("x-coordinate="+x);
                    System.out.println("y-coordinate="+y);
                    xc=x;
              yc[i]=y;
              System.out.println("i="+i);
              i=i+1;
         public Dimension getPreferredSize()
    return new Dimension(500,500);
         public void paintComponent(Graphics g)
    super.paintComponent(g);
              Graphics2D g2D = (Graphics2D)g;
              //g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
              g2D.setColor(Color.GREEN);
              for (j=0;j<i;j=j+2)
                   g2D.drawLine(xc[j],yc[j],xc[j+1],yc[j+1]);

    camickr wrote:
    "How to Use Layered Panes"
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html
    Add your video component to one layer and your non-opaque panel to another layer.Did you try that with JMF? It does not work for me. As I said, the movie seems to draw itself always on top!

  • Hello, is there a way for making a photo transparent with iPhoto are another software?

    Hello, is there a way for making a photo transparent with iPhoto are another software?

    Not with iPhoto, but different apps have different capabilities.
    There are a couple of considerations: How is this transparent image to be used? In a Deskop Publishing environment something like Pages' Instant Alpha might be useful. Or if you're trying to overlay one image on another on a photograph then some editor that supports layers would be required.
    Further, Jpegs as a format doesn't support transparency so you'll need to work ina  file format that does.
    But if you can explain what you're hoping to do we might be able to point you in a more useful direction.
    In order of price here are some suggestions for editors:
    Seashore (free)
    The Gimp (free)
    Graphic Coverter ($45 approx)
    Acorn ($50 approx)
    Pixelmator ($50 approx)
    Photoshop Elements ($75 approx)
    There are many, many other options. Search on MacUpdate or the App Store.
    You can set Photoshop (or any image editor) as an external editor in iPhoto. (Preferences -> General -> Edit Photo: Choose from the Drop Down Menu.) This way, when you double click a pic to edit in iPhoto it will open automatically in Photoshop or your Image Editor, and when you save it it's sent back to iPhoto automatically. This is the only way that edits made in another application will be displayed in iPhoto.

  • Making JPanels transparent changes the look of the frame

    Hi,
    I wanted to set a background image on my internal frame, which contains more edits and buttons. This was easy, I set the image as background on the frame panel, then made all the JPanels containing elements transparent (=opaque(false)) so that the background is now visible.
    Now my problem is that when there is no image to load (or no background wished) the former look of my frame became strage: there are 2 nouances of grey, the old gray from buttons is still there, but the containing panels are in a darker gray then the before. It seems to hang together with the new transparent panels. Setting a background color doesn't seem to help too...Do you have any idea, how could I restore the old "same gray overall" look?
    Thanks for helping,
    maria

    You may find the answer at the link shown below:
    http://java.sun.com/products/jfc/tsc/articles/swing2d/index.html
    Without seeing any code, I am guessing that the container's background is showing thru the first transparent component and the next's component's background is being added on top of it.
    ;o)
    V.V.

  • Imported image and making white space transparent...

    I need to make the white space around an image transparent without having to use the clipping mask tool. In Freehand, you simply click a button and the white background disappears. I need to use that exact technique to hide the white background.
    How can I do this in InDesign?
    Thank you.

    There's quick, and there's right. They're rarely in the same space.
    To make a transparent background can be a complex and fussy process. While InDesign could include a general tool to do so, it would likely be inferior to actually making the image background transparent in a native image editing tool.
    I've found most such embedded features to be adequate only for low end work - e.g., they leave a background halo on the image, or a noisy edge, or other image problems. I really don't see it as a flaw or omission that ID forces you to use a proper tool to create the background transparency.

  • Advice for JPanel transparency idea

    Hi!
    I've spent all day reading about the CardLayout and JLayeredPane and am confused as to which route to take.
    Here's what I'm planning to build:
    - One frame containing three panels.
    - Each panel holds an invididual image and and stretches to the extents of the frame, thus the panels sit on top of each other.
    - I would like to be able to change the order of the panels
    - Here's the killer: I'd like to change the transparancy of the top panel (either partially or completely) so that I can peer through to the panel below.
    Any advice would be appreciated. Many thanks...

    To summarise (thanks J_Rooze for advice):
    - Setting the AlphaComposite value before calling super.paintComponent(g2) will change the transparency of the whole panel.
    - Performance will drop in the order of ~40%, but using J_Rooze's suggestion to force the OpenGL rendering pipeline (above) completely remedies this (is there a similar hack for java3D?? :-).
    - Using these panels with JLayeredPane worked completely for my spec (top post).
    - I also tried them in CardLayout, however, whilst I could get the top panel to go transparent the underneath panel would not show through. This might not necessarily be a problem for other specs.
    - Panels should be .setOpaque(false) to eliminate crazy phasing effects.
    Here's my working code for reference:
    import java.awt.*;
    import javax.swing.JPanel;
    public class DisplayPanel extends JPanel{
         private boolean antiAlias;
         private float alpha = 1.0f;
         public DisplayPanel(boolean setAntiAlias) {
              antiAlias = setAntiAlias;
              this.setOpaque(false);
         public void setAlpha(float a) {
              alpha = a;
              if (alpha > 1) alpha = 1.0f;
              if (alpha < 0) alpha = 0.0f;
              repaint();
         public float getAlpha() {
              return alpha;
         protected void paintComponent(Graphics g) {
              Graphics2D g2 = (Graphics2D)g;
              AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getAlpha());
              g2.setComposite(ac);
              super.paintComponent(g2);
              // for speed
              g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
              g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
              if (antiAlias) g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              //draw commands go here
    }Edited by: .eD on May 7, 2008 4:46 AM

  • JPanel Transparency Causes Artifacts

    I am working on a battleship game an have a JPanel class which has a transparent color for a background (setBackground(new Color(1f, 1f, 1f, .25f));). When the panel is repainted, lots of artifacts appear and the background is one-half as transparent. Also, the current text is repainted on top of the previous text. I have searched the bug database and found that this is a common issue and can be worked around using setOpaque(false) and overriding paintComponent to paint the background. I did this, but there are still a significant amount of artifacts on the panel. Any ideas? Has anyone else seen this issue before? If so, how did you solve it?
    Conditions:
    J2SDK1.5.0 Beta1
    Windows XP Pro (2 Different Machines)
    Here's my paintComponent code:
    public void paintComponent(Graphics g)
         g.setColor(new Color(1f, 1f, 1f, .25f));
         g.fillRect(0, 0, getWidth(), getHeight());
         super.paintComponent(g);
    }Thanks
    Blake
    [email protected]

    The artifacts are not caused by paintComponent. I posted it for reference to my second question. Maybe I should have seperated the questions for more clarity.
    1. How do I work around the artifact issue?
    2. I've read of a custom background painting workaround. Has anyone else heard of it? Did the paintComponent method body I posted in the initial post correctly address this issue?
    To answer your question, I initialize no explicit Threads of any kind. I tried, but it made the artifacts worse.
    Thanks.
    Blake
    [email protected]

  • A way of making window look transparent

    I'm using the following method to make a window look transparent: whenever a frame is moved, it makes a screenshot of the underliying area and displays it as its background
    but, unfortunately, this doen't work in this example ????
    public class MyFrame extends JFrame implements ComponentListener{
    private Image image;
    public MyFrame(){
    super();
    this.addComponentListener(this);
    public void componentHidden(ComponentEvent e){}
    public void componentShown(ComponentEvent e){}
    public void componentResized(ComponentEvent e){}
    public void componentMoved(ComponentEvent e){
    try{
    image = (new Robot()).createScreenCapture(new Rectangle(getX(), getY(), 200, 200));
    repaint();
    }catch(Exception ex){ ex.printStackTrace(); };
    public void paint(Graphics g){
    if(image != null){
    g.drawImage(image, 0, 0, this);

    May it will not help too much, but I know that a transparent window, isn't transparent, in truth.
    What this windows really is doing is a screenshot of desktop background, and printing it at window background. So, I think prefectly normal that problems as your happen somtimes.
    best wishes

  • Making a Photo Transparent

    This is likely a rather rudimentary question with an equally rudimentary answer, but I'm a new Mac owner. I need assistance in turning a full-color .png or .jpg picture transparent, so that I can place it over a iMovie clip. How can this be accomplished. Additionally, an instructions on how to overlay a picture on a iMovie clip would be helpful

    Welcome to the Apple Discussions.
    That’s one for the iMovie forum, really. I don’t think iMovie 08 or earlier dos this kind of multi-track video? I know they’ve added Picture in Picture in iMovie 09. It’s quite simple to do with an app like Final Cut.
    I would post on the iMovie forum and find out if what you want to do is actually possible.
    Regards
    TD

  • Making a button transparent

    I'm designing a Japplet with JButton but i dont know how to make my buttons background transparent
    i read the color class tutorial but i actualy didnt understand it
    it gives lots of values like fload arrays or something
    can somebody tell me how can i make my buttons background transparent?
    Thanks

    It's always good to send an example as you finally did.
    That helps to find a solution:
    package applet;
    import javax.swing.*;
    import java.awt.*;
    public class backgammon extends JApplet{
        public Icon pulicon,bgIcon;
        private Image pul_s,background;
        public JButton b1;
        public void init(){
            //set layout:
            getContentPane().setLayout(null);
            this.setSize(744, 536);
            //set button:
            pul_s = getImage(getCodeBase(),"images/pul_sari.gif");
            pulicon = new ImageIcon(pul_s);
            b1 = new JButton(pulicon);
            b1.setBounds(50,50,42,42);
            b1.setContentAreaFilled(false);
            b1.setBorderPainted(false);
            getContentPane().add(b1);
            //set background:
            background = getImage(getCodeBase(),"images/background.jpg");
            bgIcon = new ImageIcon(background);
            JLabel bg = new JLabel(bgIcon);
            bg.setBounds(0,0,getWidth(),getHeight());
            getContentPane().add(bg);
    }

  • Making the background transparent in export from cinema 4d to AE CC

    I'm using Cinema 4D to create a 3d object and then import it into AE CC.  When I import it in, the grey grid in the background is visible. I want to make the background transparent, so that all you can see is the object in AE.  How can I do this?

    This is not a matter of transparency. You are seeing what you are seeing because you are looking at the draft software rendering result.
    Choose Standard (Final) from the Renderer menu in the Cineware effect.

  • Making a color transparent

    Hi all
    i am designing a software that visualises property prices of houses. so i have images of houses all over the map. what i want to do is when i click a certain button, it shades the most expensive houses with dark red and least expenses houses with lighter red.
    the problem i am facing is that, once i try to shade over the area of where a house image is, the house image disappears. the color is put in the fore ground and the house image disappears, so i was wondering if there is any way to make a color transparent so that the shade of red can be seen as well as the image of the house
    thanks in advance
    regards

    Sure, just set an alpha value smaller than 1.0 (float) resp. 255 (int):
    http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Color.html
    -Puce

  • Making a color transparent in many layers

    I'm using Photoshop Elements 5.0
    I want to create an animated gif using many layers of jpegs. Each layer is a picture of the earth (round) surrounded by the color black to the edge of the jpeg (square). However, I would like to make the outer border of black the transparent color.
    How can I easily make the color black the transparent color in all the layers of the gif, such that when the globe rotates on a white page the black is transparent?
    Thanks,
    Ken

    > Is there a way to do more than one layer at a time
    Assuming the area is identical in shape and location, then Don has given you the answer. Otherwise no.
    I just realised that I'm helping someone with an animated GIF again. And I am driven mad by Web pages which include the darned things...

  • Making a frame Transparent

    I'm trying to make a small program that displays some text in a frame, but the frame should be transparent so the user can see the text, and whats behind the frame on the desktop. I've looked for a way to set the color of the current frame, or just the Alpha but no luck. Any help is greatly appreciated.

    Well, it was impossible under 1.3. AFAIK, they've done nothing within Merlin to change this.
    The best you'll be able to come up with is a component that picks up whatever is sitting underneath it within the component heirarchy and respects what its parent is trying to paint. Of course, once you hit the top component in the heirarchy (i.e. the frame), you're pretty much stuffed. ;-)
    Hope that helps!
    Martin Hughes

  • Pdf import: making bkg NOT transparent

    I'm trying to place pdf pages in Keynote and parts of them are coming up transparent (most were created in Quark or Illustrator). Is there a way in Keynote to set the bkg color to white for the placed graphic? I know we can paste a white block or page behind the graphic either in Keynote or within the program which created it, but I'd rather not add an extra step or two.
    Is there a way to have the contents of an image box both display the image AND have a non-transparent colored background?
    Thanks! - j
      Mac OS X (10.4.10)  

    If they were created in Quark and you exported directly from Quark to PDF, then any transparencies are still not flattened. If you have Acrobat 7.x or newer you can use PDF Optimizer (advanced menu/optimize PDF) and look for an option called "Flatten transparency", Select the values you require (ie: Low end for web, high end for print) and then optimize the file. Once it is done, do NOT save as, simply close and you will have no more transparent backgrounds. You can do the same in Illustrator before the files are imported into Quark or saved as PDF's. The other alternative is to make sure that Quark picture boxes have a fill of 'white' or '0% black', then writing PS instead of PDF and distilling it to create your PDF. Postscript does not support transparancies, so it flattens any it sees while creating the PS file, then the resulting PDF (after distilling) is flattened and you don't need to optimize it.
    Good luck.
    The above assumes that you have image in the white areas, not simply blank space. Blank space is blank space, you would need to draw white boxes behind everything (What a pain!)

Maybe you are looking for