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");
logPanel.add(label);

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

mainPanel.add(logPanel, c);

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

contentPane.add(mainPanel);
return contentPane;
}

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

TextAreaExample demo = new TextAreaExample();
frame.setContentPane(demo.createContentPane());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

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


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.

    ReplyDelete