I've been searching the internet for a way to specify the size of a component within a JPanel, but I haven't been able to find anything that has worked. The best answer I came across was to override the getPreferredSize(), getMaximumSize(), and getMinimumSize() methods of the component, but the component still took up the entire available space within the JPanel.

For the sake of argument, let's say I'm trying to define a custom size for a JTextArea inside a JPanel using a BoxLayout. What is the best way to stop the Layout Manager from resizing my components to take up the entire available space?

Thanks in advance for the help!

5 Years
Discussion Span
Last Post by abyss776

What layout manager are you using?

Can you post a small program that compiles and executes and shows the problem.


Thanks for the reply! Sure, here's a short code that demonstrates the issue.

import javax.swing.*;
import java.awt.*;

public class TestSwingClass extends JFrame {
  public TestSwingClass() {
  public void initUI() {
    JTextArea txt = new JTextArea(5,5);
    //none of this seems to have any effect
    txt.setMaximumSize(new Dimension(100,100));
    txt.setMinimumSize(new Dimension(100,100));
    txt.setPreferredSize(new Dimension(100,100));
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(txt, BorderLayout.CENTER);
  public static void main(String args[]) {
    TestSwingClass sc = new TestSwingClass();

As you can see, I'm using a BorderLayout. The BorderLayout seems to resize the component to take up the entirety of the center area. However, I would like to be able to set my own custom size for the JTextArea.


What I do is wrap the component in a new JPanel (Flow Layout),
and place the new JPanel inside of your formatting JPanel (Border Layout).
Unless you're going for a full screen effect of your Border JPanel,
you could also wrap that in another JPanel (Flow Layout).

Votes + Comments
While not exactly what I'm looking for, your solution is very effective and does solve the problem. Thanks a lot!

Thanks, hfx642. I actually tried that with a BoxLayout shortly before you posted that solution, and it worked well. Still, I'm wondering if there is perhaps a more direct method that doesn't involve using a different layout within the BorderLayout.

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.