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.

Similar Messages

  • 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

  • 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

  • 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

  • JTable have no resize cursor under a JLayeredPane

    Hi,
    i have over my JScrollPane a JLayeredPane to show infotext.
    When the JLayeredPane is over the JScrollpane you can resize the column but the JTable show no resize Cursor.
    Does anybody know why?
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayeredPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    public class NoResizeCursorDemo extends JFrame
      public NoResizeCursorDemo()
        JTable table = new JTable( new DefaultTableModel( new String[]{ "aaa", "bbb" }, 10 ) );
        JScrollPane scrollPane = new JScrollPane( table );
        InfoLayer layer = new InfoLayer( scrollPane );
        add( layer );
      public static void main( String[] args )
        NoResizeCursorDemo frame = new NoResizeCursorDemo();
        frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
      class InfoLayer extends JLayeredPane
        private final JComponent wrappedComponent;
        public InfoLayer( JComponent wrappedComponent )
          this.wrappedComponent = wrappedComponent;
          setLayout( null );
          add( wrappedComponent, JLayeredPane.DEFAULT_LAYER );
          setInfoText();
        private void setInfoText()
          add( new JLabel( "Info......" ), JLayeredPane.POPUP_LAYER );
          revalidate();
        @Override
        public Dimension getPreferredSize()
          return wrappedComponent.getPreferredSize();
        @Override
        public void doLayout()
          Dimension size = getSize();
          Component layers[] = getComponents();
          for ( Component layer : layers )
            layer.setBounds( 0, 0, size.width, size.height );
    }Thanks

    Hi,
    I had almost the same problem with JTable and JSplitPane, the components worked fine, but cursor did not change when require.
    I already had in place mouse events dispatching in my top layer. It passed all events to the components underneath (see example in [Glass Pane Demo Project|http://java.sun.com/docs/books/tutorial/uiswing/examples/components/GlassPaneDemoProject/src/components/GlassPaneDemo.java]; in my case the listener was the content panel of the top layer).
    And now here is the trick around the cursor. Within the custom dispatch method I've called the following:
    this.setCursor(comp.getCursor());
    where "this" is the content panel of the layer and comp is the component where mouse event passed to.
    Hope that helps!
    Regards,
    Sergey

  • 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!!!

  • 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);
    }

  • JApplet does not resize correctly

    Hello,
    I'm trying to practice with JLayeredPane in JApplet.
    The problem is that when i resize the applet JButton b3 is painted "as a background", and still works as a JButton.
    Why doesn't it resize correctly as the other JComponent do?
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JLayeredPaneDemo extends JApplet {
         public void paint(Graphics g) {
              final JLabel l1 = new JLabel("LABEL 1",JLabel.CENTER);
              final JLabel l2 = new JLabel("LABEL 2",JLabel.CENTER);
              final JLabel l3 = new JLabel("LABEL 3",JLabel.CENTER);
              resize(400,300);
              l1.setOpaque(true);
              l1.setBackground(Color.blue);
              l1.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l2.setOpaque(true);
              l2.setBackground(Color.green);
              l2.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l3.setOpaque(true);
              l3.setBackground(Color.yellow);
              l3.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l1.setBounds(0,0,100,100);
              l2.setBounds(30,30,100,100);
              l3.setBounds(60,60,100,100);
              getLayeredPane().add(l1,new Integer(1));
              getLayeredPane().add(l2,new Integer(2));
              getLayeredPane().add(l3,new Integer(3));
              JButton b1 = new JButton("LABEL 1 ON TOP");
              JButton b2 = new JButton("LABEL 2 ON TOP");
              JButton b3 = new JButton("LABEL 3 ON TOP");
              b1.setBounds(220,0,150,40);
              b2.setBounds(220,40,150,40);
              b3.setBounds(220,80,150,40);
              b1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l2)>getLayeredPane().getLayer(l3))
                             getLayeredPane().setLayer(l1,new Integer(getLayeredPane().getLayer(l2)+1));
                        else
                             getLayeredPane().setLayer(l1,new Integer(getLayeredPane().getLayer(l3)+1));
              b2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l1)>getLayeredPane().getLayer(l3))
                             getLayeredPane().setLayer(l2,new Integer(getLayeredPane().getLayer(l1)+1));
                        else
                             getLayeredPane().setLayer(l2,new Integer(getLayeredPane().getLayer(l3)+1));
              b3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l1)>getLayeredPane().getLayer(l2))
                             getLayeredPane().setLayer(l3,new Integer(getLayeredPane().getLayer(l1)+1));
                        else
                             getLayeredPane().setLayer(l3,new Integer(getLayeredPane().getLayer(l2)+1));
              add(b1);
              add(b2);
              add(b3);
    }If i use the init() method instead of the paint(Graphics g) method JButton b3 is painted as large as possible since the beginning.
    thanx in advance :)

    Swing related questions should be posted in the Swing forum.
    If i use the init() method instead of the paint(Graphics g) methodWell, thats the proper way to write a Swing applet. The code for building the GUI should be in the init() method. You never need to override the paint() method of the JApplet.
    Components will not be automatically resized when the size of the applet changes. A layered pane does not use a layout manager, therefore it is up to you to manually change the size of each component. You can add a ComponentListener to the applet to be notified when the size changes.

  • URGENT: Heap space problems with image resizing

    I'm creating a Swing program, with an InternalFrame-type interface. One of the frames contains a .gif file background and then primitive G2D objects are drawn on top of it.
    The background image loads and displays fine at its original size, but I've added code for when the window resizes, and resizing the image causes the VM to give me an OutOfMemory exception.

    I tried this without any problem (with a gif of 137 kb):
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ImageFrame extends JFrame {
        public ImageFrame() {
            initComponents();
            Toolkit T=this.getToolkit();
            im0=T.getImage("C:\\sophie.gif");
            MediaTracker mediaTracker = new MediaTracker(this);
            mediaTracker.addImage(im0, 1);
            try {
                mediaTracker.waitForID(1);
            } catch (InterruptedException ie) {
                System.err.println(ie);
            jInternalFrame1.add(new MyPanel());
        private void initComponents() {
            jDesktopPane1 = new JDesktopPane();
            jInternalFrame1 = new JInternalFrame();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            jInternalFrame1.setResizable(true);
            jInternalFrame1.setVisible(true);
            jInternalFrame1.addComponentListener(new ComponentAdapter() {
                public void componentResized(ComponentEvent evt) {
                    jInternalFrame1ComponentResized(evt);
            jInternalFrame1.setBounds(0, 0, width, height);
            jDesktopPane1.add(jInternalFrame1, JLayeredPane.DEFAULT_LAYER);
            getContentPane().add(jDesktopPane1, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-800)/2, (screenSize.height-500)/2, 800, 500);
        private void jInternalFrame1ComponentResized(ComponentEvent evt) {
            width=jInternalFrame1.getWidth();
            height=jInternalFrame1.getHeight();
        public static void main(String args[]) {
            new ImageFrame().setVisible(true);
        private int width=500,height=300;
        private Image im0;
        private JDesktopPane jDesktopPane1;
        private JInternalFrame jInternalFrame1;
        class MyPanel extends JPanel {
            public void paint(Graphics g1) {
                g1.drawImage(im0,0,0,width,height,this);
                g1.dispose();
    }

  • 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.

  • How to setBounds for components inside JLayeredPane

    Hello,
    Please help me find a solution to the following: I'm trying to construct a JPanel inside which there is a JLayeredPane. In the JLayeredPane there is (among others) a JScrollPane with a view onto a table. When the top panel resizes, I need to track the new size of the JLayeredPane and setBounds for the components inside the JLayeredPane for them to render correctly filling out the entire space available. I don't want to setBounds to a high threshold because on one of the layers there is a JScrollPane which needs to precisely fill the entire area of JLayeredPane to show the scroll controlls in their correct position. Here is a much simplified sample code:
    jLayeredPane.addComponentListener(new ComponentAdapter() {
    public void componentResized(ComponentEvent e) {
    setScrollPaneBounds();
    public void componentShown(ComponentEvent e) {
    setScrollPaneBounds();
    private void setScrollPaneBounds() {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    Dimension size = jLayeredPane.getSize();
    myJScrollPane.setBounds(0, 0, size.width, size.height);
    The problem in the above code is that the behaviour is random, when I resize the frame the myJScrollPane.setBounds sometimes sets the bounds, and other times it does not. Also I see the rendering of the JScrollPane 'leading' other changes higher up in the component hierarchy.
    Please help me solve these problems.
    Thanks.

    Thanks for suggestion, but that doesn't change anything. The biggest problem is the order of events. In the JFrame there is some complex layout with nested JSplitPane (2) and when I resize the window this little JLayeredPane seems to redraw FIRST and should be one of the last as it is deep in the component tree. When I take away the ComponentListener I have installed onto the JScrollPane, then event sequence is all good, but the setBounds on the JScrollPane is never called and the sizing becomes incorrect.
    Marcin.
    - CryptoHeaven Team

  • Avoid repaint in JLayeredPane components

    I have a program including a JLayeredPane that contains a JComponent and a JPanel. Both components are set on different layers of the JLayeredPane.
    I use the JPanel for painting, so I want to avoid unnecessary repaints if I can. The problem is that when I resize the JComponent using setBounds(), the JLayeredPane performs a repaint, and consequently, the JPanel too.
    How can I avoid the repaint propagation through all the JLayeredPane? I tried to use setIgnoreRepaint(true), but it didn't seem to work.
    If you need to see some code, just ask. Thanks in advanced. :)

    Sorry for not sending my SSCCE before; there was mealtime here. Thanks for your code anyway, I'll have a look now to see if I get any idea.
    This is my code. What I'd like to avoid it's to display the setence "inner painted" (it means that the paintComponent() method of the innerPanel has been triggered):
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import javax.swing.BoxLayout;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.event.MouseInputListener;
    public class SelectionFrame implements MouseInputListener {
        private final static int CURSOR_WIDTH = 2;
        private final static int ALPHA_SELECTION_INT = 20;
        private JFrame frame;
        private JScrollPane scrollPane;
        private JPanel innerPanel;
        private JPanel outerPanel;
        private JComponent transComponent;
        private JLayeredPane layeredPane;
        private boolean cursorEnabled;
        private boolean selectionEnabled;
        private Color bgColor;
        public SelectionFrame() {
            cursorEnabled = true;
            selectionEnabled = true;
            frame = new JFrame();
            frame.setTitle("Adilo Selection");
            frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),
                    BoxLayout.X_AXIS));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setMinimumSize(new Dimension(400, 300));
            bgColor = Color.CYAN;
            innerPanel = new JPanel()  {
                @Override
                protected void paintComponent(Graphics g)   {
                    System.out.println("inner painted");
            innerPanel.setBackground(bgColor);
            outerPanel = new JPanel();
            outerPanel.setBackground(Color.BLUE);
            outerPanel.setBounds(0, frame.getHeight() / 3, frame.getWidth(), frame.getHeight() / 3);
            transComponent = new JComponent()
                @Override
                public void paintComponent(Graphics g)
                    Color selectionColor = new Color(255 - bgColor.getRed(),
                            255 - bgColor.getGreen(),
                            255 - bgColor.getBlue(),
                            ALPHA_SELECTION_INT);
                    g.setColor(selectionColor);
                    g.fillRect(0, 0, getSize().width, getSize().height);
            layeredPane = new JLayeredPane();
            layeredPane.add(innerPanel, new Integer(1));
            layeredPane.add(outerPanel, new Integer(2));
            layeredPane.add(transComponent, new Integer(3));
            scrollPane = new JScrollPane();
            scrollPane.setViewportView(layeredPane);
            innerPanel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
            innerPanel.addMouseListener(this);
            innerPanel.addMouseMotionListener(this);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
        private int initXPos;
        public void mousePressed(MouseEvent e) {
            initXPos = e.getX();
            if(cursorEnabled)    {
                transComponent.setBounds(e.getX(), 0, CURSOR_WIDTH, frame.getHeight());
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mouseDragged(MouseEvent e) {
            int xPos = e.getX();
            if(selectionEnabled)    {
                if(xPos > initXPos) {
                    transComponent.setBounds(initXPos, 0, xPos - initXPos, frame.getHeight());
                else    {
                    transComponent.setBounds(xPos, 0, initXPos - xPos, frame.getHeight());
        public void mouseMoved(MouseEvent e) {
        public void mouseClicked(MouseEvent e) {
        public static void main(String[] args) {
            new SelectionFrame();
    }

  • Auto-resizing JPanel  on mouseEntered

    Hello,
    I am looking for a little advice. I want to try and make a JPanel resize on mouseEntered. I want the JPanel to be be almost hidden until the mouse is over and I want it to grow in size gradually rather than appear instantly. The Panel will share space with a JEditorpane which will occupy the majority of the space but resize to allow to the JPanel to grow in size.
    --Hidden
    ///////////////////////////////////////////////////////////////////////////////////// - Base panel
    ////////////////////////////////////////////////////////////////////////////////////// - JPanel almost hidden
    /                               JEditorPane                                             /
    ////////////////////////////////////////////////////////////////////////////////////// - Base panel
    --On Mouse Over
    /////////////////////////////////////////////////////////////////////////////////////// - Base panel
    /                          JPanel now showing                                 /
    /                         JEditorPane                                                  /
    //////////////////////////////////////////////////////////////////////////////////////// - Base panelThe JPanel will start of with a height of say 5 and when the mousentered event is fired it will grow over the space of half a second or so to a height of about 80. When the Mouse exists I want to to go back to it's original position.
    I have seen this technique used on some desktop applications I have used in the past and I would like some advice on how best to accomplish this in Swing.
    Has anyone done this before, or if not which way might it be possible?
    I am not expecting code, just some ideas on an approach. I am not really that good when it comes to Swing.
    BTW, I have tried already with a JPanel as the base panel and a JLayeredPane but the JPanel I wish to resize ignore the calls to setSize, possible becuase it has various components embedded on to it.
    Cheers.

    BTW, I have tried already with a JPanel as the base panel and a JLayeredPane but the JPanel I wish to resize ignore the calls to setSize, possible becuase it has various components embedded on to it. When using JLayeredPane, the trick would be to use setBounds( ) instead.
    Basically to achieve this you would need a simple javax.swing.Timer and the necessary MouseListeners. Consider creating a subclass of JPanel where you will attach the listener code. Once, the mouseEnters, you'll probably need to set a boolean which indicates that the panel should grow, and fire the Timer. The Timer's actionPerformed method should check the boolean to determine whether to grow the panel or shrink it. The changes to the panel should be done through setPreferredSize( ).
    Consider removing all the items in the Panel before shrinking and re-adding them only when the Panel is fully grown. This may help improve performance.
    This feature may cause your application to suffer a bit in terms of appearance when the panel growing or shrinking unless a suitable LayoutManager is choosen. Cant suggest any unless I try it my self.
    ICE

  • Help please on image resizing

    How do you resize images (I can't find anything in the APIs).
    At the moment I have an application with an inherited layeredPane and images (from inherited JLabels) drawn on top.
    The pane currently has no layout, if I resize the application everything else resizes but the images stay the same.
    Would anyone be able to show me what I have to change to enable the images to resize, help would be appreciated.
    public class BoardPanel extends JLayeredPane
        public BoardPanel()
        //Overwrite abstract painting method
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            //draw Image at size of panel starting at 0,0
         g.drawImage(backgroundImage,0,0,this.getWidth(), this.getHeight(), null);
        private Image backgroundImage = new ImageIcon("./Images/Board.gif").getImage();
    public class PieceIcon extends JLabel
        //Create new image with the piece (symbol) chosen by the player
        public PieceIcon(String symbol,int pNum)
            playerNumber = pNum;
            pieceImage = new ImageIcon("./Images/"+symbol+".jpg").getImage();
            setOpaque(false);
        public void paintComponent(Graphics g)
           super.paintComponent(g);
           g.drawImage(pieceImage,boardPos[0][(MainFrame.getPlayer(playerNumber).getCurrentBoardPos())],
                                  boardPos[1][(MainFrame.getPlayer(playerNumber).getCurrentBoardPos())],this);
        private Image pieceImage;
        private int playerNumber;
        private static int[][] boardPos = //load of absolute values, change to proportionate values if images can be resized
    public class MainFrame extends JFrame
        /** Creates new form JFrame */
        public MainFrame()
            initGUI();
            pack();
        private void initGUI()
           //create components and add to frame, including:
            JPanel content = new JPanel();
            getContentPane().add(content, java.awt.BorderLayout.CENTER);
            content.add(boardIcon, java.awt.BorderLayout.CENTER);
            //Create the board Pane
               boardIcon.setPreferredSize(new java.awt.Dimension(500,500));
            //start at (x,y) 0,0, with height/width (600,600)
                boardIcon.setBounds(0,0,600,600);  //does this have to be set again if window is resized?
            boardIcon.setLayout(null);      
        public void createPieces()
           //method called in main once player names and details have been enterd
           playerPieces = new PieceIcon[this.getNumPlayers()];
           for(int i=0; i<this.getNumPlayers(); i++)
              //Create new icon with players piece selection and number selection
              playerPieces[i] = new PieceIcon(this.getPlayer(i).getPiece(),i);
             //Add piece at depth of '10' (default layer is 0 so just above other board components)
             boardIcon.add(playerPieces,new Integer(10));
    //label size of board, piece drawn at specific point within board
    playerPieces[i].setBounds(0,0,boardIcon.getHeight(),boardIcon.getWidth());
    private static BoardPanel boardIcon = new BoardPanel();
    private PieceIcon[] playerPieces;
    Thanks in advance

    You need to use g.drawImage(image, dest.x, dest.y, dest.width, dest.height, source.x, source.y, source.width, source.height, null)
    It's in the Graphics API. It will scale the image on the fly. The destination coordinates should be the panel you want to paint on.

  • From JPanel to JLayeredPane

    Hi all, I'm having some trouble with something I though it would be easier...
    I had a JApplet with a main JPanel I added directly to the contentPane, and worked ok, something like...
    JPanel jpan = functionThatCreatesJPanel();
    Container contentPane = getContentPane();
    contentPane.add(jpan);... but now, I need to display some screens over this panel, so I was thinking in using a JLayeredPane, add the old JPanel as background layer, and add new JPanels over it. Is this idea correct?
    JLayeredPane lp = new JLayeredPane();
    lp.setPreferredSize(new Dimension(975,575));
    lp.add(functionThatCreatesJPanel(),new Integer(1));
    lp.setVisible(true);
    Container contentPane = getContentPane();
    contentPane.add(lp);and my applet stays gray! no error messages are shown...
    what do you think?
    thanks!

    Well, this might be a little late to help you, but I was experiencing the same problem. I solved it by adding a component listener on the layered pane that relayed resize events to the contained JPanel, like so:
    layeredPane.addComponentListener(new java.awt.event.ComponentAdapter() {
                public void componentResized(java.awt.event.ComponentEvent evt) {
                     backgroundPanel.setSize(layeredPane.getSize());
            });This appears to correctly paint the panel.

Maybe you are looking for

  • What is the most powerful books for Windows server 2008 and R2?

    Hi, There are many books out there that cover Windows server 2k8 and its R2 successor but i wonder which ones to focus on. In the same time, all books are for one purpose, "Windows Server 2008". Each author has his/her own view on the platform. I don

  • Mac keeps crashing fatally

    Hi - I'm in major need of help if anyone can? I'd be so graetful. Over the last 2 months or so my iMac has been crashing on a regular basis (increasing in frequency to every 2/3 days now) - whereby the grey screen comes up and my mac has to be restar

  • Mac Mini first boot and bluetooth keyboard not recognised

    Hi Apple Support Community- I have just purchased a brand new Mac Mini and App Wireless Keyboard.  Unfortunately upon first boot, the Mac Mini is requesting I connect my bluetooth keyboard by switching it on, however even though the green light flash

  • Display mirroring doesn't fit on external monitor

    I have a Philips FlatTV that is 1280x720 and a new MacBook that is 1280x800. When I connect the external monitor, the top, bottom and left side of the screen are truncated. The right side is aligned to the edge. I lose about 1" of the display image o

  • Variable declaration in user exit?

    Hi, How can i declare variable in user exit? Is it the same way we declare in report? Thanks & Regards, Abhijit