Question

I am trying to create a form in MigLayout. I want for any text fields to be labeled with a small JLabel preceding it, with the text field growing as space is available. I am successfully able to do this in the following code:

JFrame frame = new JFrame("Test");
JPanel panel = new JPanel(new MigLayout("", "fill", ""));
panel.add(new JLabel("Testing"));
panel.add(new JTextField(), "growx, pushx, wrap");
frame.setContentPane(panel);
frame.pack();
frame.setMinimumSize(new Dimension(400, 100));
frame.setPreferredSize(new Dimension(400, 100));
frame.setVisible(true);

The result looks like this, which is as expected (the JLabel is the minimum necessary size, the JTextField takes up the rest of the area):

enter image description here

However, if I put a JEditorPane below this and have it span the length of the whole window, the JLabel becomes larger and grows if I enlarge the window. The code change looks like this:

...
panel.add(new JTextField(), "growx, pushx, wrap");
//New line of code here:
panel.add(new JEditorPane(), "growx, pushx, span");
frame.setContentPane(panel);
...

Which causes a result that I do not expect (the JLabel has grown):

enter image description here

I've tried to fix this by adding MigLayout parameters for the JLabel, like "growx 0" and "shrink", but this doesn't seem to have any effect on the size of the label.

How can I prevent the JLabels from growing in a situation like this?

Was it helpful?

Solution

I figured it out! The problem is with the parameter on the JEditorPane:

panel.add(new JEditorPane(), "growx, pushx, span");

It turns out that when using span, growx, pushx is unnecessary (because it already grows in size) and when used in conjunction with this, it creates the effect shown above. My guess is that growx applies to all cells marked by span, but pushx only applies to the first cell.

So span makes the component take up multiple cells, they all were assigned the default growx weight, but pushx only makes the first cell grow.

So the proper way to fix the line is simply:

panel.add(new JEditorPane(), "span");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top