add conponents to panel

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thashi
    New Member
    • Aug 2007
    • 2

    add conponents to panel

    how to add components to the panel on the fly
    following code is not work
    JButton b=new JButton("hjkhk" );
    jPanel3.add(b);
    setContentPane( jPanel3);

    I hope your help
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by thashi
    how to add components to the panel on the fly
    following code is not work
    JButton b=new JButton("hjkhk" );
    jPanel3.add(b);
    setContentPane( jPanel3);

    I hope your help
    Don't set the contentPane to be the panel. Instead use [CODE=java]getContentPane( ).add(jPanel3);[/CODE]

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by r035198x
      Don't set the contentPane to be the panel. Instead use [CODE=java]getContentPane( ).add(jPanel3);[/CODE]
      As a matter of fact setting the content pane to a JPanel does work. All the JFrame
      wants is that its content pane should be a JComponent and it must be opaque.

      The JFrame's add() method delegates to its content pane's add() method and all
      JComponents have such a method (inherited from the Container class), so there's
      no problem here.

      You could wonder why to create a JPanel in the first place because the original
      content pane is a JComponent and thus a Container (with a BorderLayout) so it
      can do the job as well.

      kind regards,

      Jos

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Originally posted by JosAH
        As a matter of fact setting the content pane to a JPanel does work. All the JFrame
        wants is that its content pane should be a JComponent and it must be opaque.

        The JFrame's add() method delegates to its content pane's add() method and all
        JComponents have such a method (inherited from the Container class), so there's
        no problem here.

        You could wonder why to create a JPanel in the first place because the original
        content pane is a JComponent and thus a Container (with a BorderLayout) so it
        can do the job as well.

        kind regards,

        Jos
        I just thought they may want other panels to appear together with that panel (judging from the variable names they have).
        The setContentPane is certainly not the reason why their code "is not work".

        Comment

        Working...