JLayeredPane

Hi, I'm having a problem with JLayeredPane. My background image won't show up. Any suggestions?
Thanks in advance          
JFrame frame = new JFrame();
          Toolkit t = frame.getToolkit();
          Dimension d = t.getScreenSize();
          int width = (int)d.getWidth();
          int height = (int)d.getHeight();
          frame.setBounds(0,0,width,height);
          JLabel main = new JLabel();
          ImageIcon mainIcon = new ImageIcon("background.jpg");
          main.setIcon(mainIcon);
          frame.getLayeredPane().add(main, new Integer(10));
          main.setVisible(true);

http://java.sun.com/docs/books/tutorial/uiswing/components/problems.html
Use getLayeredPane.add(component, int).

Similar Messages

  • Can't get JLayeredPane to work

    Hi,
    I'm trying to use the JLayeredPane as part of a large application, but I can't get a small example to work... What else do I need to set before I can see my JLabel?
    package views;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    public class Test extends JFrame {
          * @param args
         public static void main(String[] args) {
              new Test();
         public Test()
              super("Test");
              this.setVisible(true);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setSize(new Dimension(200, 200));
              JLayeredPane pane = (JLayeredPane) this.add(new JLayeredPane());
              pane.add(new JLabel("Hello World"), new Integer(0));
              this.add(pane);
    }Edited by: TheDauntless on Oct 24, 2009 12:55 PM

    TheDauntless wrote:
    Thanks, that seems to work. You're welcome.
    I have a follow up question: How can I get my JLabel to take up the entire parents width & height?
    I usually use a GridBagLayout (with fill=horizontal, weightx=1, heightx=1, gridx=0, gridy=0), but I can't always get it to work. Is there a better way to make sure the size is 100%x100% ?I know that I use GridBagLayout, but only sparingly and only when other layouts (including nested layouts) won't work. I think that there are several in this same camp. In your situation, you could easily just use a BorderLayout and add the JLabel BorderLayout.CENTER.

  • Problem removing components from JLayeredPane

    Hi all,
    I have a problem showing and hiding components on a JLayeredPane. It goes Something like this:
    In my application I have a button. When this button is pressed I use getLayeredPane to get the frames layered pane. I then add a JPanel containing a number of labels and buttons onto that layered pane on the Popup layer. The panel displays and funcitons correctly.
    The problem comes when I try to remove the panel from the layered pane. The panel does not dissappear and I am no longer able to click on anything else in the frame!
    If anyone has any ideas how to get around this or what the problem might be I'd be very greatful to hear it. Sample code follows:
          * Called when the button on the frame is pressed:
          * @param e
         public void actionPerformed(ActionEvent e)
                    JLayeredPane mLayredPane = getLayeredPane();
              int x = 0, y = 0;
              Container c = this;
              while (true)
                   c = c.getParent();
                   if (c != null)
                        x += c.getLocation().x;
                        y += c.getLocation().y;
                        if (c instanceof JRootPane)
                             break;
                   else
                        break;
              mPanel.setBounds(x, y, 235, 200);
              mLayredPane.add(mPanel, JLayeredPane.POPUP_LAYER);
    //And when a listener fires from the panel I use
    mLayredPane.remove(mPanel);
    //To remove it from the layered pane and in theory return the
    //app to the state it was before the panel was displayedThanks again...

    The problem is you only removed it within the program, without actually removing it from the display. If that makes any sense, or whether thats your problem at all.
    If you are only using this line.
    mLayredPane.remove(mPanel);
    I think if you tell it to repaint and revalidate it should work, though i have never used LayeredPane.
    mLayredPane.repaint();
    mLayredPane.revalidate();

  • Create an image of a JLayeredPane 's content

    hi there,
    we have a problem here: we'd like to create one image out of a JLayeredPane`s content. but the only thing we get is a gray box which size is the size of the JLayeredPane.
    the purpose is: we're developing a graphic tool where you can draw and arrange objects in the JLayeredPane(which is in a JScrollPane). and now we're implementing the print-function which allows to print the graphs over several pages, therefore it is neccessary to have an image(*.jpeg) for our printpreview-window. the preview-window and the printfuntion are nearly implemented and the only problem is that we cant make an image of the JLayerdPane's content.
    maybe you have an idea or codesamples...
    thanks a lot in advance!!
    george

    1. Getting any JComponent to render onto a buffered image isn't a problem -- just call paint, passing it a graphics object backed by that buffered image.
    2. Writing an image to a file isn't a problem: use javax.imageio.ImageIO.
    Some code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Ex {
        public static void main(String[] args) {
            JFrame f = new JFrame("Ex");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final JLayeredPane pane = new JLayeredPane();
            Border b = BorderFactory.createEtchedBorder();
            pane.add(createLabel("DEFAULT_LAYER", b, 00, 10), JLayeredPane.DEFAULT_LAYER);
            pane.add(createLabel("PALETTE_LAYER", b, 40, 20), JLayeredPane.PALETTE_LAYER);
            pane.add(createLabel("MODAL_LAYER", b, 80, 30), JLayeredPane.MODAL_LAYER);
            pane.add(createLabel("POPUP_LAYER", b, 120, 40), JLayeredPane.POPUP_LAYER);
            pane.add(createLabel("DRAG_LAYER", b, 160, 50), JLayeredPane.DRAG_LAYER);
            f.getContentPane().add(pane);
            JPanel south = new JPanel();
            JButton btn = new JButton("save");
            btn.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    save(pane);
            south.add(btn);
            f.getContentPane().add(south, BorderLayout.SOUTH);
            f.setSize(400,300);
            f.show();
        static JLabel createLabel(String text, Border b, int x, int y) {
            JLabel label = new JLabel(text);
            label.setOpaque(true);
            label.setBackground(Color.WHITE);
            label.setBorder(b);
            label.setBounds(x,y, 100,20);
            return label;
        static void save(JComponent comp) {
            int w = comp.getWidth(), h = comp.getHeight();
            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setPaint(Color.MAGENTA);
            g2.fillRect(0,0,w,h);
            comp.paint(g2);
            g2.dispose();
            try {
                ImageIO.write(image, "jpeg", new File("image.jpeg"));
            } catch(IOException e) {
                e.printStackTrace();
    }Why does the saved image have a magenta background? JLayerPane, by default, is non-opaque. You can set it to be opaque and choose its background color, as you like.

  • How to use JLayeredPane with LayoutManager

    Hi!
    I'm having problems with JLayeredPane. I simply cannot understand how to use it. I would like to have a button on top of my JDialog (The Dialog should have two components, a custom drawing panel and a JButton to close it with (want to keep the window undecorated, thus the need for the close-button)).
    AboutDialog
    |******Animation here***<- ------- CustomPanel
    |**************************|
    | *********and here*******|
    | ******** ______*********|
    | &here | Close | &here |<-----JDialog
    | ******** ----------*********|
    +------------------^---------- --+
    ...........................|
    ..........................JButton
    This is what i tried, after finding out that JLayeredPane has a null layout:
    class FilledLayeredPane extends JLayeredPane {   
    public FilledLayeredPane() {
         super();
         addComponentListener(new ComponentAdapter() {
              public void componentResized(ComponentEvent e) {
              compRes();
    //Resize all components to fit
    protected void compRes() {
         Component[] comps = getComponents();
         Rectangle bounds = getBounds();
         for (int i=0; i<comps.length;i++)
         ((JComponent) comps).setBounds(bounds);
    Then i added two panels with different z-order. One panel with the button, and also the CustomPanel.
    However, the resize algorithm is ugly, and it doesn't work as it should at all. I'm getting really random behaviour from this...
    How am i supposed to do?? I want the LayeredPane to layout the components i add to it! At least make sure that all added component fill up the size of the LayeredPane...
    Plz help!

    Forgive me, that was bs. I get correct componentResized notificatiuons every single time.
    The problem is: My manual updates of the JPanel inside the JLayeredPanel DO work, and the JPanel is resized correctly (otherwise I would see elements from behind shinig through).
    BUT the JPanel doesn't always take the fact that it is manually resized as a reason to layout its components!!!
    In my case, it works, as far as I've seen, EXACTLY EVERY SECOND TIME!!!
    The solution is indeed VERY simple: After manually resizing an element with a layout that is non-null, call layout() on that element!!!
    In my case,
    jpanelXXX.setSize(size); jpanelXXX.layout();works wonders!!!

  • JTable in JLayeredPane - resize table header cursor

    Hey everybody, I have searched all over this forum and the net for an answer to this problem. I have a class that adds a JComponent to a JLayeredPane in the default layer. In another layer above the default layer is a JComponent that exists only to provide a 'pretty' image border with round corners that overlap the component below it. It works and looks very good. The only problem I have found is that if the JComponent that is added (in the default layer) is a JTable the cursor no longer changes to the resize cursor (<->) when mousing over the table header column edges. I can still resize the columns but I need to have the cursor change to indicate that the colums can be resized for user friendliness. I assume that the mouse events are getting trapped by the upper layer in the JLayeredPane and aren't reaching the JTable in the lower layer as they need to.
    I have tried swapping the two layers but when I do that the corners of the component that I want to add the border to overlap over the nice round corners of the border which defeats the purpose.
    If anyone has any suggestions, or even better a solution, that would be great!
    Thanks,
    Erik

    table.getTableHeader().setVisible(false); will
    help.This is necessary, but probably not quite sufficient for picky users. You may also want to set the min, max, and preferred dimensions of the table header to 0,0, otherwise you get what looks like a top-only border.
    Michael Bushe

  • JLayeredPane - keeping all contained components filling the layeredPane

    I'm having some troubles keeping contained components inside a JLayeredPane so they're all filling the pane.
    The desired effect I want is to have a region of the window that contains two panels -- one for standard view/editing, and an overlayed transparent panel above it, which, at times, will show icons overlayed over the base panel -- basically an OSD layer over a panel that will be showing video.
    I've gone the approach of using a JLayeredPane and adding the base panel, but I'm having troubles getting it to make sure it fills the entirety of the JLayeredPane.
    I thought of several approaches:
    1.) Set up the JLayeredPane with a BorderLayout, and set the components all to CENTER, but then I realized that with BorderLayout, each position can only have one component assigned to it.
    So, this approach is a no-go. :(
    2.) Set up a ComponentListener on the JLayeredPane, listening for componentResized, and resizing the contained panels to event.getComponent().getSize(). This approach did result in a resize happening on the component I was testing, but alas, it resizes it to the original, pre-resized size! Reading the docs, and what others have said on the msg board, this seems to be going against what I'm reading and hearing about.
    Does anyone have any ideas for me? I'm all ears.
    Is there a radically different approach I could take?
    What I'm going after is kinda like the glassPane feature on a Frame, but I'm not working with a frame, just one panel inside the frame of my main application window.. And I'd like it so I could encapsulate the OSD panel in it's own derived class -- that's what I'm doing right now -- so I can have custom methods for manipulating the OSD.

    bsampieri wrote:
    For this type of situation, I usually subclass JLayeredPane and override the doLayout() method. In there, assuming you want to have everything on it's layer fill the layer it's on, just set it's bounds to (0, 0, w, h) with the width/height of the layered pane itself. Aha! That worked like a charm! Just what I was after. I need to get more comfortable altering the inner-workings of swing components through subclassing.
    If you need something more advanced, you'd have to have a way to determine which components should go where/what size.Nope -- I didn't need to subclass in this case -- I want each and every item in the JLayeredPane to fill the entirety of the container. I sorta figured that there should be a relatively easy solution to it, but I hadn't been able to figure out how, and googling it up didn't seem to result in any useful information on the subject.
    Thank you very much bsamieri!
    Here's exactly what I ended up doing:
    package com.tripleplayint.newvideopreviewermockup;
    import java.awt.Component;
    import javax.swing.JLayeredPane;
    * A panel widget that allows components to be layered on top of one another,
    * where each component fills the entirety of this container.
    * This is only useful when all but the lowest layer is set transparent, as
    * the highest opaque layer will obscure any layers below it.
    * @NOTE If one wants to move the layers to choose which one is visible, your
    * better option is to use a JPanel with the CardLayout.
    * @author kkyzivat
    public class FilledLayeredPane extends JLayeredPane {
         * Layout each of the components in this JLayeredPane so that they all fill
         * the entire extents of the layered pane -- from (0,0) to (getWidth(), getHeight())
        @Override
        public void doLayout() {
            // Synchronizing on getTreeLock, because I see other layouts doing that.
            // see BorderLayout::layoutContainer(Container)
            synchronized(getTreeLock()) {
                int w = getWidth();
                int h = getHeight();
                for(Component c : getComponents()) {
                    c.setBounds(0, 0, w, h);
    }

  • Resizing Components in a JLayeredPane

    Hello,
    I'm brand new to Java (formerly a VB man). I'm creating an application where icons are displayed on a background image and can be dragged around the window. The background image and the icons need to resize with the window.
    I've managed to get the back ground image to resize but can't work out how to get the icon images to resize as well. I also need to keep their relative positions as well.
    I have three classes which extend JFrame, JLayeredPane and JPanel to construct the display. I have attached them below.
    If anyone can help or at least point me in the right direction I would be very grateful indeed.
    Best regards
    Simon
    package imagelayers;
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SecondFrame extends JFrame
    private JLayeredPane m_layeredPane;
    private MovingImage m_movImage1, m_movImage2, m_movImage3;
    private BackgroundImage m_background;
    public SecondFrame() {
    super("Moving Images");
    setLocation(10,10);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Load the background image in a JPanel
    ImageIcon kcIcon = new ImageIcon("images/kclogo.gif");
    m_background = new BackgroundImage(kcIcon);
    setSize(kcIcon.getIconWidth(), kcIcon.getIconHeight());
    m_movImage1 = new MovingImage("images/dukewavered.gif", 0);
    m_movImage2 = new MovingImage("images/dukewavegreen.gif", 1);
    m_movImage3 = new MovingImage("images/dukewaveblue.gif", 2);
    m_background.add(m_movImage1 , JLayeredPane.DRAG_LAYER);
    m_background.add(m_movImage2 , JLayeredPane.DRAG_LAYER);
    m_background.add(m_movImage3 , JLayeredPane.DRAG_LAYER);
    m_movImage2.topLayer = 2;
    Container contentPane = getContentPane();
    contentPane.add(m_background);
    setVisible(true);
    public static void main(String[] arguments)
    JFrame frameTwo = new SecondFrame();
    package imagelayers;
    import java.awt.*;
    import javax.swing.*;
    public class BackgroundImage extends JLayeredPane
    private Image m_backgroundImage;
    public BackgroundImage(ImageIcon bg)
    m_backgroundImage = bg.getImage();
    setBorder(BorderFactory.createTitledBorder(""));
    public void paintComponent(Graphics g)
    g.drawImage(m_backgroundImage,0,0,getWidth(),getHeight(),this);
    package imagelayers;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import java.awt.*;
    import java.awt.event.*;
    public class MovingImage extends JLabel implements MouseListener, MouseMotionListener
    private Image m_theImage;
    private ImageIcon m_theImageIcon;
    private int nStartX, nStartY;
    static int topLayer;
    public MovingImage(String imgLocation, int layerNum)
    addMouseListener(this);
    addMouseMotionListener(this);
    m_theImageIcon = new ImageIcon(imgLocation);
    m_theImage = m_theImageIcon.getImage();
    setBounds(0, 0, m_theImageIcon.getIconWidth(), m_theImageIcon.getIconHeight());
    public void paintComponent(Graphics g)
    g.drawImage(m_theImage,0,0,getWidth(),getHeight(),this);
    public void mousePressed(MouseEvent e)
    JLayeredPane imagesPane = (JLayeredPane)getParent();
    imagesPane.setLayer(this,topLayer,0);
    nStartX = e.getX();
    nStartY = e.getY();
    public void mouseMoved(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mouseDragged(MouseEvent e)
    setLocation(getX() + e.getX() - nStartX, getY() + e.getY() - nStartY);
    }

    Try useing the JFrames show() method or setVisible(true) method after you have added all the other components.
    If that doesnt work use the JFrames validate() method, inherited from Container, after one of the previous methods.
    Hope this helps

  • JLayeredPane Resize

    I have two JPanels which I want to add to my JLayeredPane. The JLayeredPane has to show one of the JPanels, dependant on the state of a combobox. When the user resizes the window the JPanel inside the JLayeredPane also needs to resize. I can't get JLayeredPane to work correctly without setting the size of the JPanels (which is something I don't want to do because the size of the JPanels will be determined by the size of the window).
    I've looked a great deal to find the answer to my problem, but no luck so far. This is what I have.
              layered = new JLayeredPane();
              layered.setLayout(new BorderLayout());
              layered.setLayer(treepanel, new Integer(0));
              layered.add(treepanel,BorderLayout.CENTER);
              layered.setLayer(searchpanel, new Integer(1));
              layered.add(searchpanel,BorderLayout.CENTER);
              layered.moveToFront(treepanel); This code only shows the last added panel (searchpanel). The last line apperantly does nothing (moveToFront(treepanel)).
    How can I fix this?

    Sounds like you should be using a CardLayout, not a Layered Pane.
    "How to Use Card Layout"
    http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html
    Otherwise you will need to add a ComponentListener to the layered pane and resize the panels manually whenever the layered pane is resized.

  • Resizing an imageIcon of a jLabel on a jLayeredPane

    I have 2 questions, somewhat related:
    Question 1:
    I have a jLayeredPane with a number of jLabels of imageIcons.
    I need to resize the top imageIcon when I move a slider. To get the top component on the jLayeredPane, I use:
    Component topComponent = layeredPane.getComponent(0);However, I can't figure out how to get the image IN the jLabel IN the Component to set its size. Any ideas?
    Question 2:
    Also, it is easy to add items to a jLayeredPane. For example:
    layeredPane.add(myLabel);but how do I delete an item?

    Q1:
    Component topComponent = layeredPane.getComponent(0);
    JLabel l=(JLabel)topComponent ;
    Q2:
    layeredPane.remove(layeredPane.getIndexOf(myLabel));
    Regards,
    Stas

  • JLayeredPane - not all high layer being drawn.

    I'm getting an odd effect with a JLayeredPane in that some (but not all) of a higher layer is being hidden behind a lower layer JComponent. Is this likely to be a layout manager issue (I'm not setting one) or am I doing something else silly?
    I'd have posted some code, but the highly simplified case that I first wrote works OK, and I can't quite see the difference between it and my program. It'll take at least another day to simplify that one to make it postable. So I thought I'd ask the general question first.

    Forgive me if this counts as highjacking an old thread. Did you ever find a solution, and what was it?
    I kinda have the opposite problem: I have two JPanels in a JLayeredPane and put the relevant one of them in front depending on the situation. But when the one conatining a JList is behind, if I click where the JList is, the selected element of the list comes to front even though I don't think it should, and also some JButtons when the mouse comes over them.
    I'll ask a colleague who has more experience with JLayeredPane than I have. If I find a solution, I'll post it here. Should be glad to hear from anyone who might know anything about the problem.

  • Overlapping two JPanels on a JLayeredPane

    I am having some problems overlapping two JPanels on a JLayeredPane for some reason only one of them shows when I compile the program! Any help would be greatly appreciated
    The code is the following:
    import java.lang.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SpaceBall
    //To do the background just draw a JPanel inside another //JPanel just set the opacity of the outside one
    //to false and let
    //it hold all the components of the game
    public static void main(String[] args)
    //declaring the buttons
    JButton test=new JButton("test");
    JButton test1=new JButton("test1");
    JButton test2=new JButton("test2");
    //declaring and setting the properties of the frame
    JFrame SpaceBall= new JFrame("Space Ball");
    SpaceBall.setSize(700,650);
    //declaring the Panels
    JLayeredPane bgPanel= new JLayeredPane();
    JPanel fgPanel= new JPanel();
    JPanel topPanel= new JPanel();
    JPanel sidePanel= new JPanel();
    JPanel lowPanel= new JPanel();
    JPanel masterPanel= new JPanel();
    //adding the buttons to the corresponding panels
    fgPanel.add(test1);
    sidePanel.add(test2);
    topPanel.add(test);
    ImageIcon background= new ImageIcon("images/background.jpg");
    JLabel backlabel = new JLabel(background);
    backlabel.setBounds(0,0,background.getIconWidth(),background.getIconHeight());
    backlabel.add(test1);
    bgPanel.add(backlabel, new Integer(0));
    fgPanel.setOpaque(false);
    bgPanel.add(fgPanel, new Integer(100));
    bgPanel.moveToFront(fgPanel);
    //adding bgPanel and sidePanel to lowPanel
    lowPanel.setLayout(new GridLayout(1,2));
    lowPanel.add(bgPanel);
    lowPanel.add(sidePanel);
    //adding the Panels to the masterPanel
    masterPanel.setLayout(new GridLayout(2,1));
    masterPanel.add(topPanel);
    masterPanel.add(lowPanel);
    //getting the container of SpaceBall and adding the Panels to it
    Container cp=SpaceBall.getContentPane();
    cp.add(masterPanel);
    //displaying everything
    SpaceBall.show();
    WindowListener ClosingTheWindow=new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    SpaceBall.addWindowListener(ClosingTheWindow);

    Take a look at the section from the Swing tutorial titled "How to Use Layered Panes". It has a sample program:
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html

  • JLayeredPane with JScrollPane inside

    Hi all,
    I am making an applet with a fairly complex gui. The main part is a content window that has a jpanel with another jpanel and a jscrollpane inside, each of which have a bunch of components. From there I wanted to add a help window that popped up when you hit the help button. What I did is I got the JLayeredPane from the applet using getLayeredPane(), and I added the help window to the popup layer, and the content window to the default layer. I'm using a null layout and manually setting the bounds of everything. All the panels draw correctly, but when I open the help window, it displays inside the JScrollPane; i.e. it moves when I scroll, and the contents of the scroll pane are displayed on top of the help window. Here is some of my code, if I wasn't clear:
              //this grabs the applet's layered pane. The wrapper pane (with all the traces)
              //is on the default layer, and the help window (and any other popups) will go in the popup layer
              appletLayered = getLayeredPane();
              appletLayered.setLayout(null);
              //create the help window that will be displayed when someone presses help
              helpWindow = new HelpWindow(getCodeBase().toString());
              appletLayered.add(helpWindow, JLayeredPane.POPUP_LAYER);
              helpWindow.setBounds(50,50,400,450);
              appletLayered.add(wrapperPane, JLayeredPane.DEFAULT_LAYER);
              wrapperPane.setBounds(0,20,700,550);Does anyone know why it is doing this? Should I just do this whole thing a different way, or is there an easy solution that I'm missing.

    Swing related questions should be posted in the Swing forum.
    From there I wanted to add a help window* that popped up when you hit the help button.Then use a JDialog (or a JWindow), not a layered pane.
    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.

  • Have GridLayout in JLayeredPane

    Hi, I would like to have a JPanel with GridLayout as background and another image on top of it. So I think I have to add 2 JPanel into the JLayeredPane but it doesn't work. I wonder whether I can do it in fact, anybody know it? Thanks.
    I have my code for your reference:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MainFrame{
         public MainFrame(){
              initFrame();
         public void initFrame(){
              JFrame frame = new JFrame("Swing program");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              ImageIcon bgIcon = new ImageIcon("pic/background.jpg");
              JLabel[] bgLabel = new JLabel[4];
              for(int i=0; i<4; i++){
                   bgLabel[i] = new JLabel(bgIcon);
                   bgLabel.setBounds(50,50,200,200);
              JPanel bgPane = new JPanel(new GridLayout(2,2));
              bgPane.setPreferredSize(new Dimension(600, 600));
              for(int i=0; i<4; i++){
                   bgPane.add(bgLabel[i]);
              ImageIcon charIcon = new ImageIcon("pic/character.jpg");
              JLabel charLabel = new JLabel(charIcon);
              charLabel.setBounds(10,10,100,100);
              JPanel charPane = new JPanel();
              charPane.setPreferredSize(new Dimension(100,100));
              charPane.add(charLabel);
              JLayeredPane layeredPane = new JLayeredPane();
              layeredPane.setPreferredSize(new Dimension(600, 600));
              layeredPane.add(bgPane, new Integer(1));
              layeredPane.add(charPane, new Integer(2));
              Container contentPane = frame.getContentPane();
              contentPane.add(layeredPane);
              frame.pack();
              frame.setVisible(true);

    Error in code:for(int i=0; i<4; i++){
      bgPane.add(bgLabel);
    }should befor(int i=0; i<4; i++){
      bgPane.add(bgLabel[ i]);
    }

  • JLayeredPane help

    I need to create a GUI with a JPanel showing a plot, and on the bottom left corner I'd like to have a JTable showing some data. The LayeredPane would be real nice to do that. I tried but the objects in the LayeredPane did not resize with the window. So, my question is: is there any way to fix the objects in the LayeredPane so they resize with the window much like if it was a BorderLayout or so?
    Here is a little test I did without the plot; but it exemplifies real well what I mean:
    public class TestLayersMain extends javax.swing.JFrame {
        /** Creates new form TestLayersMain */
        public TestLayersMain() {
            initComponents();
        private void initComponents() {
            jPanel2 = new javax.swing.JPanel();
            jLayeredPane2 = new javax.swing.JLayeredPane();
            jScrollPane3 = new javax.swing.JScrollPane();
            jTextArea2 = new javax.swing.JTextArea();
            jScrollPane4 = new javax.swing.JScrollPane();
            jTable2 = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jPanel2.setLayout(new java.awt.BorderLayout());
            jScrollPane3.setViewportView(jTextArea2);
            jScrollPane3.setBounds(10, 10, 430, 280);
            jLayeredPane2.add(jScrollPane3, javax.swing.JLayeredPane.DEFAULT_LAYER);
            jTable2.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane4.setViewportView(jTable2);
            jScrollPane4.setBounds(10, 190, 200, 100);
            jLayeredPane2.add(jScrollPane4, javax.swing.JLayeredPane.POPUP_LAYER);
            jPanel2.add(jLayeredPane2, java.awt.BorderLayout.CENTER);
            getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
            pack();
       public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestLayersMain().setVisible(true);
        private javax.swing.JLayeredPane jLayeredPane2;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JScrollPane jScrollPane3;
        private javax.swing.JScrollPane jScrollPane4;
        private javax.swing.JTable jTable2;
        private javax.swing.JTextArea jTextArea2;
        // End of variables declaration                  
    }Thanks in advance!

    [url http://java.sun.com/docs/books/tutorial/uiswing/events/componentlistener.html]How to Write a Component Listener
    Try adding a ComponentListener to the LayeredPane and handle componentResized() method and then resize your components manually.

Maybe you are looking for