doing this works :

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));          
        textArea = new JTextArea();
        scrollPane = new JScrollPane(textArea);
        contentPane.add(scrollPane,BorderLayout.CENTER);
        setContentPane(contentPane);

however this doesnt :

        contentPane = new JPanel();
        textArea = new JTextArea();
        scrollPane = new JScrollPane(textArea);
        contentPane.add(scrollPane,BorderLayout.CENTER);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

i guess thats got something to do with setBorder() and setLayout() creating something like a new instance of JTextArea perhaps , something that nullifies the effect of contentPane.add(scrollPane,BorderLayout.CENTER); line , but i was hoping for a concrete answer as to why one code works and the other doesnt.

thanks in advance for your time :)

A JPanel object is initialized to use a FlowLayout, unless you specify differently when creating the JPanel. So in the second case you are adding to a FlowLayout (using a BorderLayout parameter for an unspecified result)

in the second case you are adding to a FlowLayout (using a BorderLayout parameter for an unspecified result)

that explains the null pointer exceptions i was getting , i thought the contentPane had already fitted in the panel when i called the methods on it , but they hadnt fit in , and gave me nulls.

thanks for the answer :)

  • all Layout Managers(customs too), together with JFrame.pack() are calculated on PreferredSize (based on component tree, ZOrder), first is painted last, on top JComponent

  • with some LayoutManagers is possible to resize childs, with some isn't possible (FLowLayout), or settable (GridLayout, SpringLayout, MigLayout)

  • most of LayoutManagers accepts only PreferredSize, relayout (runtime) is done by container.revalidate() & container.repaint()

  • you would need to set initial PreferredSIze (for all LayoutManagers exc AbsoluteLayout) e.g. textArea = new JTextArea(10, 15);

thanks for the detail mKorbel :) i have a feeling ill be coming back to this post when i do more with layouts. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.