Reputation: 57
Hello I was going along fine with this container by adding the panels one under another. However when I added the JTextArea it made all of the other panels have much more padding between them. How do I get rid of this extra space in between each panel? I tried to set the horizontal and vertical gap to 0 in the GridLayout constructor however, changing those values has no effect unless I make them > 5 and then they get even bigger.
setLayout(new GridLayout(5, 1, 0, 0));
pack();
setVisible(true); //Make visible
textArea = new JTextArea(initialText, 6, 25);
Upvotes: 0
Views: 44
Reputation: 285405
For example, a BoxLayout could work, but if you do this, you must recognize that you're actually setting the layout of the contentPane and not the JFrame:
//!! setLayout(new GridLayout(5, 1, 0, 0)); // Set BorderLayout
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)); // Note getContentPane()
Edit
You ask:
Setting it as BoxLayout really fixed the issue however, I am trying to undestand the logic used by getContentPane(), and then the PAGE_AXIS?
BoxLayout is unlike GridLayout, FlowLayout, and BorderLayout in that when you call the constructor, you have to pass in a reference to the component that you're adding the layout to. It looks like you're adding it to the JFrame since the class extends JFrame, and you're calling setLayout(...)
on the JFrame itself, but if you pass in this
, meaning the current JFrame instance, you'll get a runtime exception, because the setLayout(...)
method of the JFrame in fact sets the layout of the JFrame's contentPane. So to fix this, you need to pass in the JFrame's contentPane. For more on that, please read the tutorial on JFrames.
For the second part of your question, on why the second parameter to the BoxLayout constructor, BoxLayout.PAGE_AXIS
, it's for orienting your layout either horizontally or vertically. For more please read the BoxLayout tutorial and API.
This reference will get you to the pertinent Swing tutorials: Swing Info
Upvotes: 1