Swing - how to mix JTextField and JTextAreas and have same visual appearance?

I82Much picture I82Much · Apr 16, 2010 · Viewed 8.2k times · Source

I am using miglayout to create a form in which there are JTextFields (short input answers) as well as JTextAreas (Longer answers). The problem is twofold.

  1. The border placed around a Scrollpane wrapped text area does not match that of a Text Field.
  2. The width and placement of the textarea/textfield differ, causing them not to line up correctly.

alt text http://grab.by/3O0V

After changing from right/left to right/fill: alt text http://grab.by/3RMk You can see that the bounds line up, but that there are still gaps. I tried setting novisualpadding but this did not fix it.

Source code:

package test2;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;

public class Test extends JPanel {

private static final int NUM_CHARACTERS_WIDTH = 20;
private static final int NUM_ROWS = 5;
public Test() {

    setLayout(new MigLayout(
            "wrap 2",
            // Align text labels on the so their right edge meets left edge of the text fields
            "[right][left]"
            ));

    add(new JLabel("Text field:"));
    add(new JTextField(NUM_CHARACTERS_WIDTH));

    add(new JLabel("No scrollpane text area:"));
    add(new JTextArea(NUM_ROWS, NUM_CHARACTERS_WIDTH));

    add(new JLabel("Scrollpane text area:"));
    add(new JScrollPane(new JTextArea(NUM_ROWS, NUM_CHARACTERS_WIDTH)));

    add(new JLabel("Text field:"));
    add(new JTextField(NUM_CHARACTERS_WIDTH));

}


public static void main(String[] args) {
    JFrame frame = new JFrame("");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new Test();
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
}

}

What's the preferred way to mix and match jtextfield and jtextareas, while still maintaining visual harmony? I notice now that the text field has a blue highlight around it when focus is in it, as opposed to the text area... another source of visual discontinuity.

Answer

MikeM picture MikeM · Jun 3, 2014

I know this question is pretty old, but to get the border for a TextArea to match that of a TextField:

(myTextArea).setBorder(new JTextField().getBorder());

That should give a border to your TextArea like the one around a TextField.