0

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 :)

3
Contributors
4
Replies
24
Views
3 Years
Discussion Span
Last Post by somjit{}
1

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)

0

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 :)

Edited by somjit{}

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

Edited by mKorbel

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.