Results 1 to 7 of 7
  1. #1
    r00tb33r is offline Member
    Join Date
    Jun 2010
    Posts
    14
    Rep Power
    0

    Question new JLabels not showing in JPanel (doing revalidate&repaint)

    Hello all,
    I am trying to add components to a JPanel that is already displayed.
    Whenever I do something like
    Java Code:
    panel.add(new JPanel("hello world!"));
    panel.revalidate();
    panel.repaint();
    the panel stays blank.
    I've tried different layout managers as well, but lets assume its Flow for example's sake.
    I did an extensive Google search, and this is a common question, however the common solution by revalidate() and repaint() methods does not work!

    I made the following test program in NetBeans to demonstrate the problem:
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /*
     * Main.java
     *
     * Created on Jun 12, 2010, 9:51:52 PM
     */
    
    //package addcomponent;
    import javax.swing.*;
    /**
     *
     * @author Vladislav Sorkin
     */
    public class Main extends javax.swing.JFrame {
    
        /** Creates new form Main */
        public Main() {
            initComponents();
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            button = new javax.swing.JButton();
            panel = new javax.swing.JPanel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            getContentPane().setLayout(new java.awt.FlowLayout());
    
            button.setText("add label");
            button.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonActionPerformed(evt);
                }
            });
            getContentPane().add(button);
    
            panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
    
            javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
            panel.setLayout(panelLayout);
            panelLayout.setHorizontalGroup(
                panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 247, Short.MAX_VALUE)
            );
            panelLayout.setVerticalGroup(
                panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 190, Short.MAX_VALUE)
            );
    
            getContentPane().add(panel);
    
            pack();
        }// </editor-fold>
    
    [B][COLOR="Red"]    private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
            JLabel label = new JLabel("hello world!");
            panel.add(label);
            label.setVisible(true);
            panel.revalidate();
            panel.repaint();
            this.repaint();
        }[/COLOR][/B]
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Main().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify
        private javax.swing.JButton button;
        private javax.swing.JPanel panel;
        // End of variables declaration
    
    }
    Please let me know what I'm doing wrong or show a simple example of how to add a component to JPanel and make it visible after the JPanel has been displayed.
    All help is appreciated.
    Last edited by r00tb33r; 06-13-2010 at 04:43 AM. Reason: formatting

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    The last layout you want to use for this is GroupLayout. You say that you tried this with FlowLayout, yet we can't see how you've tried, nor what you did wrong. I suggest that you study the layout manager tutorial and then try to do this using some of the more user-friendly layout managers. You may find the tutorials starting here: Lesson: Laying Out Components Within a Container (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    Also note that often containers that use different layout managers are nested to achieve a goal. For instance:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class AddPanels {
      private static void createAndShowUI() {
        JPanel panel = new AddPanelsGui().getMainPanel();
    
        JFrame frame = new JFrame("Add Check Panels");
        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
          }
        });
      }
    }
    
    class AddPanelsGui {
      private JPanel mainPanel = new JPanel();
      private JPanel holderPanel = new JPanel(new GridLayout(0, 1));
      private int panelCount = 0;
    
      public AddPanelsGui() {
        int checkPanelCnt = 3;
        for (int i = 0; i < checkPanelCnt ; i++) {
          holderPanel.add(new AddPanelsCheckBoxPanel(panelCount).getPanel());
          panelCount++;
        }
        
        JButton addCheckPanelBtn = new JButton("Add Check Panel");
        JPanel southPanel = new JPanel();
        southPanel.add(addCheckPanelBtn);
        addCheckPanelBtn.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            holderPanel.add(new AddPanelsCheckBoxPanel(panelCount).getPanel());
            panelCount++;
            holderPanel.revalidate();
          }
        });
        
        JPanel innerBorderLOPanel = new JPanel(new BorderLayout());
        innerBorderLOPanel.add(holderPanel, BorderLayout.NORTH);
        JScrollPane scrollPane = new JScrollPane(innerBorderLOPanel, 
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        
        Dimension iblopSize = innerBorderLOPanel.getPreferredSize();
        iblopSize = new Dimension(iblopSize.width, 2 * iblopSize.height);
        scrollPane.getViewport().setPreferredSize(iblopSize);
        
        int eb = 10;
        mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
        mainPanel.setLayout(new BorderLayout());    
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        mainPanel.add(southPanel, BorderLayout.SOUTH);
      }
    
      public JPanel getMainPanel() {
        return mainPanel;
      }
    
    }
    
    class AddPanelsCheckBoxPanel {
      private JPanel panel = new JPanel();
    
      public AddPanelsCheckBoxPanel(int panelCount) {
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 10));
        panel.add(new JCheckBox());
        panel.add(new JLabel("Label: " + panelCount));
        panel.add(new JTextField(20));
        panel.setBorder(BorderFactory.createLineBorder(Color.black));
      }
    
      public JPanel getPanel() {
        return panel;
      }
      
    }
    Last edited by Fubarable; 06-13-2010 at 05:26 AM.

  3. #3
    r00tb33r is offline Member
    Join Date
    Jun 2010
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    The last layout you want to use for this is GroupLayout.
    OK, I'm not and now that you say that I won't.
    Quote Originally Posted by Fubarable View Post
    You say that you tried this with FlowLayout, yet we can't see how you've tried
    Really? I even highlighted it for you in the original post. I really can't add much if you aren't even looking. I will provide excerpts from my first post however:
    Java Code:
    ...
    getContentPane().setLayout(new java.awt.FlowLayout());
    ...
    And the problem
    Java Code:
    ...
        private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
            JLabel label = new JLabel("hello world!");
            panel.add(label);
            label.setVisible(true);
            panel.revalidate();
            panel.repaint();
            this.repaint();
        }
    ...
    Quote Originally Posted by Fubarable View Post
    , nor what you did wrong.
    Just a thought, you tried running the example program in my first post? I think it demonstrates the problem rather clearly.
    Quote Originally Posted by Fubarable View Post
    I suggest that you study the layout manager tutorial and then try to do this using some of the more user-friendly layout managers. You may find the tutorials starting here: Lesson: Laying Out Components Within a Container (The Java™ Tutorials > Creating a GUI With JFC/Swing)
    Thanks but I've started there, and I have studied it. Hows this relevant to the problem anyway? I have objects that aren't being shown, I'm not concerned about the alignment at this point.

    Thanks for trying but its not helpful.


    [EDIT]
    Apparently my JPanel did not inherit the layout from the parent content pane. I had a JLabel display just now, but I won't rush calling it solved.
    Last edited by r00tb33r; 06-13-2010 at 05:55 AM.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by r00tb33r View Post
    OK, I'm not and now that you say that I won't.

    Really? I even highlighted it for you in the original post. I really can't add much if you aren't even looking. ...
    I will provide excerpts from my first post however:
    Java Code:
    ...
    getContentPane().setLayout(new java.awt.FlowLayout());
    ...
    You are adding JLabels to panel not to the contentPane, and panel most definitely does not use FlowLayout but rather GroupLayout. Do you want me to point out the relevant code?


    Thanks for trying but its not helpful.
    Saying this will not motivate me to try to help further. If you are unsure about something we say, please ask for clarification, but it's not in your best interest to criticize free help that we give in our spare time.

  5. #5
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    I think he's right. If you get rid of all that GroupLayout crap-code, your code works.

    Java Code:
    import java.awt.Dimension;
    import javax.swing.*;
    
    public class RootMain extends javax.swing.JFrame {
    
      public RootMain() {
        initComponents();
      }
    
      private void initComponents() {
    
        button = new javax.swing.JButton();
        panel = new javax.swing.JPanel();
    
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.FlowLayout());
    
        button.setText("add label");
        button.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonActionPerformed(evt);
          }
        });
        getContentPane().add(button);
    
        panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        panel.setPreferredSize(new Dimension(400, 400));
    
        getContentPane().add(panel);
    
        pack();
      }
    
      private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
        JLabel label = new JLabel("hello world!");
        panel.add(label);
        label.setVisible(true);
        panel.revalidate();
        panel.repaint();
        this.repaint();
      }
    
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new RootMain().setVisible(true);
          }
        });
      }
    
      private javax.swing.JButton button;
      private javax.swing.JPanel panel;
    }

    By the way, nice job biting the hand that feeds you. Good show.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by r00tb33r View Post
    Just a thought, you tried running the example program in my first post? I think it demonstrates the problem rather clearly.

    Thanks but I've started there, and I have studied it. Hows this relevant to the problem anyway? I have objects that aren't being shown, I'm not concerned about the alignment at this point.
    And yes, I ran your code, and yes, layouts and your understanding of them are fundamental to the problem. Again, you're farking your code by using GroupLayout here. But you can choose not to listen to my recommendations if you wish. Up to you.

  7. #7
    r00tb33r is offline Member
    Join Date
    Jun 2010
    Posts
    14
    Rep Power
    0

    Default

    Actually the problem came from Swing's strange inheritance of properties from parent objects, or rather the lack of it.
    I'm a bit more used to VCL inheritance behavior where by default child objects inherit all formatting properties. Lesson learned.

Similar Threads

  1. Adding a JLabel to a JPanel - jlabel not showing
    By Bongeh in forum New To Java
    Replies: 17
    Last Post: 04-07-2010, 12:02 AM
  2. Showing JList in a JPanel
    By nico.hvi in forum AWT / Swing
    Replies: 0
    Last Post: 03-10-2010, 03:26 PM
  3. Overlapping JLabels
    By techbossmb in forum AWT / Swing
    Replies: 3
    Last Post: 09-21-2009, 04:21 PM
  4. [SOLVED] JLabel not showing on JPanel
    By onefootswill in forum New To Java
    Replies: 11
    Last Post: 08-23-2008, 02:32 PM
  5. problem with JLabels
    By geork in forum New To Java
    Replies: 3
    Last Post: 01-31-2008, 03:30 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •