Wednesday, July 23, 2008

(Auto-)Growing Panes

In another Swing-related weirdness note, it seems that a certain combination of apparently logical options regarding GridBagConstraints and a JTextArea will cause the JTextArea and enclosing JPanel to expand horizontally by gridBagContraints.ipadx pixels per step, forever.

After scratching my chin in confusion, I whittled out the following minimalish example that demonstrates the result:

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

public class TextAreaExample {
public JPanel createContentPane() {

JPanel contentPane = new JPanel();

JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// ipadx > 0 causes textarea panel to grow horizontally forever if linewrap is set!
c.ipadx = 1;

JPanel leftPanel = new JPanel();
leftPanel.add(new JLabel("Left"));
mainPanel.add(leftPanel, c);

JPanel logPanel = new JPanel();
logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.PAGE_AXIS));

JLabel label = new JLabel("Hello");

// create misbehaving textarea
JTextArea log = new JTextArea(10, 40);
log.setBorder(new LineBorder(Color.BLUE));

mainPanel.add(logPanel, c);

JPanel rightPanel = new JPanel();
rightPanel.add(new JLabel("Right"));
mainPanel.add(rightPanel, c);

return contentPane;

private static void createAndShowGUI() {
JFrame frame = new JFrame("JTextArea growth test");

TextAreaExample demo = new TextAreaExample();


public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {

I can get around it by setting a preferred size on the JTextArea (a size of 0,0 seems to do the trick without changing the initial layout), but what the hell?

1 comment:

  1. p.s. For anyone who runs into a similar problem, it can probably be avoided by first adding the component to a JScrollPane. It seems some components are expected to be placed there rather than directly in a 'normal' pane, and act the bollox otherwise.