Transparent JPanel

Hello!
I have a JFrame with a background painted on it and everything works fine so far, but when I create a JPanel in the JFrame the JPanels grey colour is laying on top of the background. So my question is how to make the JPanel transparent. I read about overriding the paintComponent method, but it didn't work, I'm probably doing something wrong.
This is what I did:
class Transparency extends JPanel {
     public Transparency() {}
     @Override
     public void paintComponent(Graphics g) {
          super.paintComponent(g);
contentPanel = new JPanel();
          contentPanel.setPreferredSize(new Dimension(mainFrame.getWidth(), 200));
          contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
          contentPanel.add(new Transparency());
          mainPanel.add(contentPanel);I would really appreciate some help!

Newly created JPanel's have their opacity set to true. This means "I guarantee that I will paint all the pixels within my bounds." For many components this amounts to simply filling in the entire bounds of the component with the background color as the first thing they paint. So by setting the opacity to false the JPanel in question will no longer be a gray blob and will allow any components beneath it to show through.
JPanel#setOpacity(false); The panel in question doesn't even need to be a custom subclass (read: delete that Transparency JPanel subclass).

Similar Messages

  • An Image JPanel, A semi-transparent JPanel, and non-opaque components

    This is a more intelligent re-asking of the question I posed here: http://forum.java.sun.com/thread.jspa?threadID=579298&tstart=50.
    I have a class called ImagePane, which is basically a JPanel with an image background. The code is much like the ImagePanel posted by camickr, discussed in this topic: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=316074 (except mine only draws the image, it does not tile or scale it).
    On top of my ImagePane, I can place another component, TransparentContainer. This again extends JPanel, only a color is specified in the constructor, and it is drawn at about 70% opacity. This component is meant to help increase the readability of text components that blend with the background image, without blocking out the background image completely.
    This works very well, until I need to add a component, like, say, a non-opaque JRadioButton in a ButtonGroup. When you select a new JRadioButton at runtime, the semi-transparent JPanel fills with a combination of a completely opaque color (the one specifies to the TransparentContainer) and garbage from the non-opaque component being redrawn.
    I have noticed that the UI is restored to being non-messed up if you place another application window on top of it and then move it. So apparently, one solution is to redraw the entire UI, or just the part that has the JRadioButton on it, every time the radio button is clicked. However, this seems unnecessarily complicated. It seems to me that I am missing something in my TransparentContainer's paintComponent() method. Does anyone have any ideas?
    Here is my TransparentContainer code, if it will help:
    import java.awt.AlphaComposite;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import javax.swing.JPanel;
    public final class TransparentContainer extends JPanel
         /* Private Fields: For use only by this class.
          *  These fields hold information needed by more
          *  than one method of this class.
         private boolean fullTransparencyEnabled;
         private Color baseColor;
         private Color outerBorderColor;
         private Color innerBorderColor;
         private int obw;
         private int ibw;
         private int cbw;
         /* -- START OF METHODS -- */
         /* public TransparentContainer(Color color, boolean fullTrans)
          *   Initiallizes the transparent container object
          *   with 'color' as its base color.
         public TransparentContainer(Color color, boolean fullTrans)
              fullTransparencyEnabled = fullTrans;
              baseColor = color;
              Color borders[] = findBorderColors();
              outerBorderColor = borders[0];
              innerBorderColor = borders[1];
              obw = 3;
              ibw = 1;
              cbw = obw + ibw;
         /* private Color[] findBorderColors(Color base)
          *   Calculates the colors for the outer and inner
          *   borders of the object based on the base color.
         private Color[] findBorderColors()
              Color borders[] = new Color[2];
              int colorData[] = new int[9];
              colorData[0] = getBaseColor().getRed();
              colorData[1] = getBaseColor().getGreen();
              colorData[2] = getBaseColor().getBlue();
              colorData[3] = colorData[0] - 50;          // outerBorder red
              colorData[4] = colorData[1] - 45;          // outerBorder green
              colorData[5] = colorData[2] - 35;          // outerBorder blue
              colorData[6] = colorData[0] + 30;          // innerBorder red
              colorData[7] = colorData[1] + 30;          // innerBorder green
              colorData[8] = colorData[2] + 20;          // innerBorder blue
              /* Make sure the new color data is not out of bounds: */
              for (int i = 3; i < colorData.length; i++)
                   if (colorData[i] > 255)
                        colorData[i] = 255;
                   else if (colorData[i] < 0)
                        colorData[i] = 0;
              borders[0] = new Color(colorData[3], colorData[4], colorData[5]);
              borders[1] = new Color(colorData[6], colorData[7], colorData[8]);
              return borders;
         /* public Color getBaseColor()
          *   Returns the baseColor of this object.
         public Color getBaseColor()
              return baseColor;
         /* public Color getOuterColor()
          *   Returns the outerBorderColor of this object.
         public Color getOuterColor()
              return outerBorderColor;
         /* public Color getInnerColor()
          *   Returns the innerBorderColor of this object.
         public Color getInnerColor()
              return innerBorderColor;
         /* public boolean getFullTransEnabled()
          *   Returns whether or not this object will render
          *   with all of its transparency effects.
         public boolean getFullTransEnabled()
              return fullTransparencyEnabled;
         /* protected void paintComponent(Graphics g)
          *   Paints the component with the borders and colors
          *   that were set up in above methods.
         protected void paintComponent(Graphics g)
              Graphics2D g2d = (Graphics2D) g;
              AlphaComposite alphaComp;
              g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
              g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                                            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
              g2d.setColor(getBaseColor());
              /* Draw the main body of the component */
              if (getFullTransEnabled())
                   alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
                   g2d.setComposite(alphaComp);
              else
                   alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
                   g2d.setComposite(alphaComp);
              g2d.fillRect(cbw, cbw, super.getWidth() - 2 * cbw, super.getHeight() - 2 * cbw);
              alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
              g2d.setComposite(alphaComp);
              /* Draw the inner border: */
              g2d.setColor(getInnerColor());
              g2d.fillRect(obw, obw, ibw, super.getHeight() - obw * 2); // left border
              g2d.fillRect(obw, obw, super.getWidth() - obw, ibw); // top border
              g2d.fillRect(super.getWidth() - cbw, obw, ibw, super.getHeight() - obw * 2); // right border
              g2d.fillRect(obw, super.getHeight() - cbw, super.getWidth() - obw * 2, ibw); // bottom border
              /* Draw the outer border: */
              g2d.setColor(getOuterColor());
              g2d.fillRect(0, 0, obw, super.getHeight()); // left border
              g2d.fillRect(0, 0, super.getWidth() + obw, obw); // top border
              g2d.fillRect(super.getWidth() - obw, 0, obw, super.getHeight()); // right border
              g2d.fillRect(0, super.getHeight() - obw, super.getWidth(), obw); // bottom border
              alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
              g2d.setComposite(alphaComp);
              g2d.dispose();
    }

    I added the main method to your TransparentContainer class ...
         public static void main(String[] args) {
              JFrame f = new JFrame("test transparent container");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              TransparentContainer tc = new TransparentContainer(Color.RED, true);
              JLabel label = new JLabel("Hello, World!");
              tc.add(label);
              f.getContentPane().add(tc);
              f.setSize(800, 600);
              f.setVisible(true);
         }...using the code you posted the label was not shown. I modified your paintComponent(Graphics g) method and I did this (see the areas in bold):
         /* protected void paintComponent(Graphics g)
          *   Paints the component with the borders and colors
          *   that were set up in above methods.
         protected void paintComponent(Graphics g)
              // Call super so components added to this panel are visible
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D) g;
              AlphaComposite alphaComp;
              g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
              g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                                            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
              g2d.setColor(getBaseColor());
              /* Draw the main body of the component */
              if (getFullTransEnabled())
                   alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
                   g2d.setComposite(alphaComp);
              else
                   alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
                   g2d.setComposite(alphaComp);
              g2d.fillRect(cbw, cbw, super.getWidth() - 2 * cbw, super.getHeight() - 2 * cbw);
              alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
              g2d.setComposite(alphaComp);
              /* Draw the inner border: */
              g2d.setColor(getInnerColor());
              g2d.fillRect(obw, obw, ibw, super.getHeight() - obw * 2); // left border
              g2d.fillRect(obw, obw, super.getWidth() - obw, ibw); // top border
              g2d.fillRect(super.getWidth() - cbw, obw, ibw, super.getHeight() - obw * 2); // right border
              g2d.fillRect(obw, super.getHeight() - cbw, super.getWidth() - obw * 2, ibw); // bottom border
              /* Draw the outer border: */
              g2d.setColor(getOuterColor());
              g2d.fillRect(0, 0, obw, super.getHeight()); // left border
              g2d.fillRect(0, 0, super.getWidth() + obw, obw); // top border
              g2d.fillRect(super.getWidth() - obw, 0, obw, super.getHeight()); // right border
              g2d.fillRect(0, super.getHeight() - obw, super.getWidth(), obw); // bottom border
              alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
              g2d.setComposite(alphaComp);
              // Do not dispose the graphics
              // g2d.dispose();          
         }...seems to work fine now. Perhaps you should also add methods or additional constructors so the user can easily change the transparency level...and add some javadoc comments to your constructors ...at a first glance I did not know what fullTrans was
    public TransparentContainer(Color color, boolean fullTrans)good luck!!

  • How to draw an image on transparent JPanel?

    I want to draw an image on the transparent JPanel. How to do it?
    I do like this:
    ( In constructor )
    setOpaque(false);
    String imageName = "coral.jpg";
    iimage_Bg = Toolkit.getDefaultToolkit().getImage(imageName);
    ( In paintComponent( Graphics g ) )
    Graphics2D g2D = (Graphics2D) g;
    g2D.drawImage( iimage_Bg, 0, 0, getWidth() , getHeight() , Color.white, null );
    But it doesn't work. Please help me!
    Thank you very much.
    coral9527

    Check the values that are returned from getWidth() and getHeight(). If they either are zero, then paintComponent(Graphics g) never gets called by the components paint(Graphics g) method. I cannot see the how this component has been added or displayed so can give no advice on how you can guarantee getting a valid size. If you have simply added it to a JFrame and called pack(), the size will be zero, as the panel does not contain any components (you would not have this problem if you were adding a JLabel with an ImageIcon for example). Try not packing the frame, and giving it a valid size.

  • Problem with multiple transparent JPanels

    Hi,
    I'm currently trying to implement some kind of message box that can fade in and out. This message box is a subclass of JComponent, the message it contains can be an arbitrary Swing-Component.
    The message container and the message itself have the same background color. When fading, the (partly transparent) colors of the of the container and the message are added, which I do not want.
    Here are two images to illustrate my problem:
    What I have: http://www.inf.tu-dresden.de/~ab023578/javaforum/reality.gif
    What I want: http://www.inf.tu-dresden.de/~ab023578/javaforum/wish.gif
    Here is the code:
    import java.awt.*;
    import javax.swing.*;
    public class Main {
        static float transparency = 0f;
        public static void main(String[] args) {
            JPanel jpBack = new JPanel() {
                protected void paintComponent(Graphics g) {
                    Graphics2D g2d = (Graphics2D)g;
                    g2d.clearRect(0, 0, getWidth(), getHeight());
                    g2d.setColor(getBackground());
                    AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
                    g2d.setComposite(alpha);
                    g2d.fillRect(0, 0, getWidth(), getHeight());
            jpBack.setBackground(Color.WHITE);
            jpBack.setLayout(null);
            JPanel jpContainer = new JPanel();
            jpContainer.setBackground(Color.RED);
            jpContainer.setLayout(null);
            JPanel jpMessage = new JPanel();
            jpMessage.setBackground(Color.RED);
            JLabel jlMessage = new JLabel("MESSAGE");
            jpBack.add(jpContainer);
            jpContainer.add(jpMessage);
            jpMessage.add(jlMessage);
            jpContainer.setBounds(10, 10, 120, 100);
            jpMessage.setBounds(10, 10, 100, 50);
            JFrame frame = new JFrame();
            frame.setBounds(0, 0, 150, 150);
            frame.setBackground(Color.WHITE);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(jpBack);
            frame.setVisible(true);
            for (double a = 0; true; a += 0.01D) {
                try {
                    Thread.sleep(10);
                catch (InterruptedException e) {}
                transparency = (float)Math.abs(Math.sin(a));
                jpBack.repaint();
    }I understand that the Porter-Duff-Rule SRC_OVER causes the container to be drawn over the message (or vice versa) and both of them over the background. I think what I need is a way to handle the whole jpContainer-Panel and all its subcomponents as a single source image. Is that possible?

    Thank you for your answer, Sarcommand. Unfortunately the test program I provided is a bit too simple as your solution works here but not for my original problem. :|
    Let me explain what I want to achieve and why.
    I'm writing a tool for algorithm visualisation. Currently I am dealing with a parsing algorithm (having compontents such as an automaton with an input tape, output tape and a stack). Those components (containers) can contain multiple JComponents (GraphicalObjects), which display a BufferedImage that can be altered during the animation.
    I want to create my message windows the same way. A container that contains GraphicalObjects (or, if necessary, any other Swing component). One GraphicalObject has a very limited field of responsibility: mereley displaying its information.
    Aligning the GraphicalObject is one of the container's responsibilities.
    What I'm currently trying to do is to put my GraphicalMessage into the center of a container, leaving an offset on the left/right/upper/lower side. This is why I need the same background color for both the GraphicalMessage and the MessageContainer, I don't want the user to see that there are actually two JComponents on top of each other.
    While I could use another approach for text messages I prefer this one as I would be able to fade arbitrary Containers and their GraphicalObjects .
    Here is the code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    public class Main {
        static float transparency = 0f;
        public static void main(String[] args) {
            JPanel jpBack = new JPanel() {
                protected void paintComponent(Graphics g) {
                    Graphics2D g2d = (Graphics2D)g;
                    g2d.clearRect(0, 0, getWidth(), getHeight());
                    g2d.setColor(getBackground());
                    AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
                    g2d.setComposite(alpha);
                    g2d.fillRect(0, 0, getWidth(), getHeight());
                    super.paintComponent(g);
            jpBack.setBackground(Color.WHITE);
            jpBack.setLayout(null);
            JPanel jpContainer = new JPanel();
            jpContainer.setBackground(Color.RED);
            jpContainer.setLayout(null);
            GraphicalMessage msg = new GraphicalMessage();
            jpBack.add(jpContainer);
            jpContainer.add(msg);
            jpContainer.setBounds(10, 10, 120, 100);
            msg.setBounds(10, 10, 160, 60);
            JFrame frame = new JFrame();
            frame.setBounds(0, 0, 150, 150);
            frame.setBackground(Color.WHITE);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(jpBack);
            frame.setVisible(true);
            float stepSize = 0.01f;
            float step = stepSize;
            for (float a = 0; true; a += step) {
                try {
                    Thread.sleep(10);
                catch (InterruptedException e) {}
                if (a >= 1) {
                    step = -stepSize;
                    a -= stepSize;
                if (a <= 0) {
                    step = stepSize;
                    a += stepSize;
                    msg.updateInternalContent();
                    msg.redraw();
                transparency = a;
                jpBack.repaint();
    class GraphicalMessage extends JComponent {
        private String text;
        private Graphics2D ig2d;
        private BufferedImage image;
        public GraphicalMessage() {
            setLayout(null);
            image = new BufferedImage(100, 50, BufferedImage.TYPE_INT_ARGB);
            ig2d = image.createGraphics();
            ig2d.setColor(Color.BLACK);
            ig2d.setBackground(Color.RED);
            ig2d.setFont(new Font("Courier New", Font.BOLD, 20));
            updateInternalContent();
            redraw();
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.drawImage(image, 0, 0, null);
        public void redraw() {
            ig2d.clearRect(0, 0, image.getWidth(), image.getHeight());
            ig2d.drawString(text, 0, 20);
        public void updateInternalContent() {
            text = String.valueOf((int)(Math.random() * 10000));
    }A possibility to erase the text from the BufferedImage without having to draw a rectangle would help me as well.

  • Multiple transparent JPanels paint problem (smearing strings)

    I created full screen JWindow application.
    I created three panels:
    MainPanel - non transparent
    PPIPanel - transparent
    GlassPanel - transparent.
    All three panel and JWindow has the same bounds. Then I added PPIPanel and GlassPanel to MainPanel and then I added MainPanel to JWindow.
    MainPanel.add(PPIPanel);
    MainPanel.add(GlassPanel);
    JWindow.getContentPane().add(MainPanel);
    Whole application displays Air Traffic Situation comming from RADAR. MainPanel is a black background with airways, PPIPanel displays aircrafts and GlassPanel is MouseEvent listener for ZOOM, CENTER and other mouse operations.
    The painting code is always placed in paint(Graphics g) metod of each component. All aircraft are painted on the transparent PPIPanel with small dot fillOval() and two BOLD strings g.drawString("Aircraft")descibing aircraft.
    paint(Graphics g) {
    g.setColor(Color.GREEN);
    g.setFont(bold font);
    iterate Collection of aicrafts {
    g.fillOval(x,y,4,4);
    g.drawString(x+3,y+3,"Aircraft xxx");
    g.drawString(x+3,y+18,"Flight level");
    The situation is changing every 4 seconds and every 4 seconds special Thread calls repaint() method on PPIPanel to referesh the situation.
    The main problem is garbage remaining after refresh. Some aircrafts has smeared label after repaint ( probably because multiple transparent panels).
    What are your proposals to solve the problem. I'm just a java begginer so I need clear explenation (i.e. code example).

    just to make it clear
    paint(Graphics g) {
    super.paint(g)
    g.setColor(Color.GREEN);
    g.setFont(bold font);
    iterate Collection of aicrafts {
    g.fillOval(x,y,4,4);
    g.drawString(x+3,y+3,"Aircraft xxx");
    g.drawString(x+3,y+18,"Flight level");
    or
    paintComponent(Graphics g) {
    g.setColor(Color.GREEN);
    g.setFont(bold font);
    iterate Collection of aicrafts {
    g.fillOval(x,y,4,4);
    g.drawString(x+3,y+3,"Aircraft xxx");
    g.drawString(x+3,y+18,"Flight level");
    should work..
    Cheers
    Mike

  • How to give Common Background color for all JPanels in My Swing application

    Hi All,
    I am developing a swing application using The Swing Application Framework(SAF)(JSR 296). I this application i have multiple JPanel's embedded in a JTabbedPane. In this way i have three JTabbedPane embedded in a JFrame.
    Now is there any way to set a common background color for the all the JPanel's available in the application??
    I have tried using UIManager.put("Panel.background",new Color.PINK);. But it did not work.
    Also let me know if SAF has some inbuilt method or way to do this.
    Your inputs are valuable.
    Thanks in Advance,
    Nishanth.C

    It is not the fault of NetBeans' GUI builder, JPanels are opaque by default, I mean whether you use Netbeans or not.Thank you!
    I stand corrected (which is short for +"I jumped red-eyed on my feet and rushed to create an SSCCE to demonstrate that JPanels are... mmm... oh well, they are opaque by default... ;-[]"+)
    NetBeans's definitely innocent then, and indeed using it would be an advantage (ctrl-click all JPanels in a form and edit the common opaque property to false) over manually coding
    To handle this it would be better idea to make a subclass of JPanel and override isOpaque() to return false. Then use this 'Trasparent Panel' for all the panels where ever transparency is required.I beg to differ. From a design standpoint, I'd find it terrible (in the pejorative sense of the word) to design a subclass to inconsistently override a getter whereas the standard API already exposes the property (both get and set) for what it's meant: specify whether the panel is opaque.
    Leveraging this subclass would mean changing all lines where a would-be-transparent JPanel is currently instantiated, and instantiate the subclass instead.
    If you're editing all such lines anyway, you might as well change the explicit new JPanel() for a call to a factory method createTransparentJPanel(); this latter could, at the programmer's discretion, implement transparency whichever way makes the programmer's life easier (subclass if he pleases, although that makes me shudder, or simply call thePanel.setOpaque(false) before returning the panel). That way the "transparency" code is centralized in a single easy to maintain location.
    I had to read the code for that latter's UI classes to find out the keys to use (+Panel.background+, Label.foreground, etc.), as I happened to not find this info in an authoritative document - I see that you seem to know thoses keys, may I ask you where you got them from?
    One of best utilities I got from this forum, written by camickr makes getting these keys and their values very easy. You can get it from his blog [(->link)|http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/]
    Definitely. I bit a pair of knucles off when discovered it monthes after cumbersomely traversing the BasicL&F code...
    Still, it is a matter-of-fact approach (and this time I don't mean that to sound pejorative), that works if you can test the result for a given JDK version and L&F, but doesn't guarantee that these keys are there to stand - an observation, but not a specification.
    Thanks TBM for highlighting this blog entry, that's the best keys list device I have found so far, but the questions still holds as to what specifies the keys.
    Edited by: jduprez on Feb 15, 2010 10:07 AM

  • HELP!!! How to create a modal JPanel

    Hi
    I've been creating an applet that uses transparent JPanels to draw boxes that look like windows.
    I'm in need, now, to create one that asks for user input (ie "click the OK button") and that blocks the current thread and other panels until the user has answered.
    It's totally similar to a windows message box.
    How do i do it????
    I've been taking examples from this tech tip (http://java.sun.com/developer/JDCTechTips/2001/tt1220.html) that explains almost everything (but uses JInternalFrame), and also 2 ways of doing the thread-blocking work:
    One way uses a worker thread to compose the UI and wait() while the java dispatcher thread does the app events (action, paint) and notifyAll() when the user presses "OK".
    In the other way, the author copied the code from EventQueue's dispatchEvent() and created a dispatcher thread into the modal JFrame, so that events could be processed without having to use another thread.
    I think this last method is a hack because of portabilityu issues, for example code in my dispatchEvent() (JRE1.6.0) contains more checks and cases than the code he postet in that page.
    I think I would have problem running similar code on a previous or future version of the JRE.
    Anyway I haven't succeeded yet to wake up the waiting thread when the user has clicked OK. The notifyAll method executes, no exception is thrown, but the other thread remains asleep.
    Here's my code (note the "synchronized" keywords)
    synchronized public int show(String title, String message, int buttons, boolean isError) {
            if (isError)
                jptBox = new TLPanel(title, new Color(104,10,11), new Color(234,30,34), new Color(241,79,83));
            else
                jptBox = new TLPanel(title, new Color(6,29,108), new Color(80,103,184), new Color(120,138,200));
            jptBox.setBounds(TLStartup.centerSize(400, 100));
            btn1 = new JButton("OK");
            btn1.setBounds(180, 75, 40, 20);
            btn1.addActionListener(new ActionListener() {
                public synchronized void actionPerformed(ActionEvent e) {
                    this.notify();
            jptBox.add(btn1);
            cnt.add(jptBox);
            cnt.setComponentZOrder(jptBox, 0);
            try {
                this.wait();
            } catch (Exception ex) {
                System.out.println(ex.toString());
            return MB_ANSWER_YES;
        }

    I put a boolean variable test=true into my class, and modified the code to check it into the waiting cycle:
            try {
                while (test)
                    this.wait(1000);
            } catch (Exception ex) {
                System.out.println(ex.toString());
            }and to reset it into the actionPerformed:
            btn1.addActionListener(new ActionListener() {
                public synchronized void actionPerformed(ActionEvent e) {
                    test = false;
                    this.notifyAll();
            });And HOW COME it does work now ??? (with some delay)

  • JPanel overlay which grabs all MouseEvents

    Hi all.
    I'm getting stuck with an OverlayLayout and a transparent JPanel.
    What I have is a JPanel with several components on it (Textfields, Comboboxes, ..)
    In the running application I need to be able to re-arrange the components using
    drag & drop but this feature can be disabled so the UI behaves like every other you know.
    (You can think of this as a minimalistic GUI designer).
    My approach was to place another (transparent) JPanel on top of it using OverlayLayout to
    be able to drag ghost copies of my components around with the mouse.
    This panel can be switched invisible so dragging is disabled.
    This works for components which do not react on mouse events for themselves
    (JLabels, ..) but not for textfields.
    What I would need is a transparent layer which is able to grab all MouseEvents so the
    components on the underlying panel will not receive them (textfields don't get the focus, buttons don't get clicked, ...).
    Any help really appreciated.
    Kind regards
    Carsten

    You can use a glass pane to intercept all the events. Just try to delete "Edit Me" from this text box!
    package mypackage;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GlassPanelTest extends JFrame {
        public GlassPanelTest() {
            super("Glass Panel Test");
            setBounds(10, 10, 380, 200);
            Container contentPane = getContentPane();
            contentPane.add(new JTextField("Edit Me"));
            Component glassPane = getGlassPane();
            glassPane.setVisible(true);
            glassPane.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent _e) {
                    System.out.println("caught by the glass pane");
        public static void main(String[] args) {
            GlassPanelTest app = new GlassPanelTest();
            app.setVisible(true);       
    }

  • Jtree custom selection

    I use the jTree. When an element is selected - i dont like how it looks.
    Check the screenshot : there are two selected areas - a standart one (top) and a custom one(bottom), dont pay attention to the gradient.
    The designer made an improved variant. As you can see, the selection exceeds the jTree and goes over the JPanel, which comprises the jTree.
    How can I make it like this in my app?
    P.S.
    I have an idea to make a half-transparent JPanel and place it over the tree... but I am not sure about the TRUE-ness of this solution :)

    I use the jTree. When an element is selected - i dont like how it looks.
    Check the screenshot : there are two selected areas - a standart one (top) and a custom one(bottom), dont pay attention to the gradient.
    The designer made an improved variant. As you can see, the selection exceeds the jTree and goes over the JPanel, which comprises the jTree.
    How can I make it like this in my app?
    P.S.
    I have an idea to make a half-transparent JPanel and place it over the tree... but I am not sure about the TRUE-ness of this solution :)

  • Event passing in JLayeredPane

    Hello, I have the following problem:
    Using Swing I put JButtons on a JLayeredPane. Every time I click on a button a proper event is raised. However I want to get mouse coordinates all the time the mouse is inside the JLayeredPane. Some wrong solutions:
    1. Catch the mousemove event for the JLayeredPane. When the mouse enters a JButton I don't get the mousemove event (as the JButton catches the mouse events now).
    2. Draw a transparent JPanel on top of the JButtons and catch the mousemoved event for it. I get the coordinates but JButtons don't catch mouse clicks.
    Of course a solution would be to set JButtons (and every other object inside the JLayeredPane) catch the mousemoved event. However this means you have to change these objects. Is there any "transparent" solution? Perhaps something like the solution 2 above with the addition that the mouse click event is further passed to underlay objects (JButtons)?

    I'm not aware of any 'transparent panel' solution, but you might want to check out Toolkit#addAWTEventListener(AWTEventListener listener, long eventMask). It will catch all mouseMoved events, but checking whether the event took place inside your JLayeredPane should be simple enough.

  • Code optimizing

    Hi, i have a question:
    Im going to make a 2DGame, and so i need some layers(player layers, scenario layers,decorative layer etc etc),how can I make this layer?I think i can use transparent JPanel,is true?Or JPanel isn't fast for this?

    JPanel is likely to be fast enough, yes. Anyway, my advise: code first, optimize later...
    Whatever the choice you make, updates won't take long as soon as you nicely divide your application into classes (i.e. MVC should be fine).

  • Controlling the re-sizing of widgets:

    I have read several Swing tutorials, but many are limited in their scope.
    I have been searching for a way to control the resizing of my JPanels and widgets.
    A solution I found is to use transparent JPanels that have no content or borders. I give them weights and directions that serve as counter-weights for the JPanels I want to display and control the sizing of. Here is my code:
    public class Main extends JPanel {
        public Main() {
            super(new GridBagLayout());
            GridBagLayout gbLayout = (GridBagLayout) getLayout();
            setPreferredSize(new Dimension(250, 200));
            JPanel configPanel = new JPanel();
            configPanel.setBorder(new LineBorder(Color.blue, 2));
            configPanel.setPreferredSize(new Dimension(100, 50));
            GridBagConstraints configPanelGBConstraints = new GridBagConstraints();
            configPanelGBConstraints.fill = GridBagConstraints.HORIZONTAL;
            configPanelGBConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
            configPanelGBConstraints.weightx = 0.4f;
            gbLayout.setConstraints(configPanel, configPanelGBConstraints);
            add(configPanel);
            JPanel padding = new JPanel(); // <--- empty JPanel that servers as a counter-weight to control the sizing of "configPanel"
            padding.setPreferredSize(new Dimension(150, 50));
            GridBagConstraints paddingGBConstraints = new GridBagConstraints();
            paddingGBConstraints.fill = GridBagConstraints.HORIZONTAL;
            paddingGBConstraints.anchor = GridBagConstraints.FIRST_LINE_END;
            paddingGBConstraints.weightx = 0.7f;
            gbLayout.setConstraints(padding, paddingGBConstraints);
            add(padding);
    }So far, this is working ok.
    Resizing objects in a JFrame is extremely important, and I'd like to ask if this is a "standard practices" way to handle re-sizing?
    Maybe later on, I will get bitten by this bad technique?
    What do good Swing programmers do?
    Thanks.

    camickr wrote:
    A solution I found is to use transparent JPanelsYou could probably use Box.getHorizontalStrut(...) instead.
    But I don't know exactly what you are trying to achieve and the code is not executable.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    sorry, I should of posted all my code that compiles:
    import java.lang.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Main extends JPanel {
        public Main() {
            super(new GridBagLayout());
            GridBagLayout gbLayout = (GridBagLayout) getLayout();
            setPreferredSize(new Dimension(250, 200));
            JPanel configPanel = new JPanel();
            configPanel.setBorder(new LineBorder(Color.blue, 2));
            configPanel.setPreferredSize(new Dimension(100, 50));
            GridBagConstraints configPanelGBConstraints = new GridBagConstraints();
            configPanelGBConstraints.fill = GridBagConstraints.HORIZONTAL;
            configPanelGBConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
            configPanelGBConstraints.weightx = 0.4f;
            gbLayout.setConstraints(configPanel, configPanelGBConstraints);
            add(configPanel);
            JPanel counterweight = new JPanel();
            counterweight.setPreferredSize(new Dimension(150, 50));
            GridBagConstraints counterweightGBConstraints = new GridBagConstraints();
            counterweightGBConstraints.fill = GridBagConstraints.HORIZONTAL;
            counterweightGBConstraints.anchor = GridBagConstraints.FIRST_LINE_END;
            counterweightGBConstraints.weightx = 0.7f;
            gbLayout.setConstraints(counterweight, counterweightGBConstraints);
            add(counterweight);
        public static void createAndShowGUI() {
            JFrame mainFrame = new JFrame("test");
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new Main();
            newContentPane.setOpaque(true);
            mainFrame.setContentPane(newContentPane);
            mainFrame.pack();
            mainFrame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }This works.
    So, I am just wondering if I should use the general construct that for every JComponent, it often makes sense to use an equal and opposing (sometimes transparent) JComponent to control its re-sizing?

  • Painting on JInternalFrame

    hey,
    Recently i discovered the new class of JInternalFrame and after reading the api and make it appear and etc , i want to ask one more critical question.
    i add a JInternalFrame inside a JPanel (which isn't recommended but it was too late to change :\ ). inside that JInternalFrame i wanted to appear some pictures and text. Something that normal painting on JFrame or on JPanel would work. however after overriding paintComponent(Graphics g), it still refuses to show any kind of graphics "life signs".
    Thanks in advance,
    Aviv Avitan

    i add a JInternalFrame inside a JPanel (which isn't recommended but it was too late to change :\ ). It's never too late to change.
    I really require help, please don't ignore me. You only posted your question an hour ago. Don't be so impatient. Are we allowed to get some sleep?
    Internal frames contain a content pane which is opaque, so the content pane paints over top of the custom painting. Make you content pane transparent:
    ((JPanel)internalFrame.getContentPane()).setOpaque(false);Or, do your custom painting on a JPanel and then set the panel as the content pane for the internal frame.

  • Disable UI

    is there any way to disable the UI components not using setEnabled(false)??
    i have a form which is like
    NEW(btn)   EDIT(btn)    DELETE(btn)
    PANEL-X
        JLabel    JTextField
        lables...   fileds..  buttons... combo boxes..
                                      OKAY(btn) CANCEL(btn)
    PANEL-X CLOSEAt first, the top buttons (new, edit and delete) are setEnabled(true) and all the components inside PanelX is setEnabled(false). When the user clicks the buttons, I enable the components inside the PanelX (setEnabled(true)).
    If I were designing a web app then I would use a large transparent DIV to block all the components in the PanelX.. Dont we have a similar thing in swing? like overlapping PanelX with another Transparent Jpanel and block???

    perhaps an OverlayLayout might suit
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        JButton b1 = new JButton("OK");
        JButton b2 = new JButton("Not OK");
        JPanel p1 = new JPanel(new GridBagLayout());
        JPanel p2 = new JPanel(new GridBagLayout());
        p1.setPreferredSize(new Dimension(400,150));
        p2.setPreferredSize(new Dimension(400,150));
        p1.add(b1,new GridBagConstraints());
        p2.add(b2,new GridBagConstraints());
        JPanel p3 = new JPanel();
        OverlayLayout overlay = new OverlayLayout(p3);
        p3.setLayout(overlay);
        JPanel p4 = new JPanel();
        p4.setOpaque(false);
        p3.add(p4);
        p3.add(p2);
        JFrame f = new JFrame();
        f.getContentPane().add(p1,BorderLayout.NORTH);
        f.getContentPane().add(p3,BorderLayout.CENTER);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        p4.addMouseListener(new MouseAdapter() {
          public void mousePressed(MouseEvent me) {
            System.out.println("caught by the overlayPanel");
        b1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            System.out.println("OK");
        b2.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            System.out.println("Not OK");
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Action Events from sub-components?

    I have a main Swing GUI JFrame, in this frame I have a JLayeredPane (should have named it JLayeredPain). I have a button to switch the layers (only 2 layers, one is a text area, one is a new class which I wrote) On startup the Textarea shows. I click "Switch" and the new class object ( extends JPanel) shows in the JLayeredPane. In the new object I have a JButton "Back". I would like "Back" to cause the main GUI to switch the layers back to the TextArea. I need to somehow pass the ActionEvent from the secondary class From the "Back" button to the Main GUI to call jLayer.moveToFront(TextArea). Hmmm, but I don't know how to do this... Any thoughts would be helpful.

    Use JTabbedPane instead. JLayeredPane is only useful if you have to stack a bunch of transparent layers like Adobe Illustrator does.
    JLayeredPane isn't real good at dynamically changing event listeners. In theory, JLayeredPane should direct events to the topmost layer. In practice, I could never get it to direct events to anything other than the first added component that had any listeners. Changing the order of the layers had no effect. In the end, I added an extra transparent JPanel on top with listeners to trap the events and perform the corresponding action on the correct layer. I'll be this is exactly how Adobe Illustrator is implemented.

Maybe you are looking for