JTextField margin doesnt work with border

querman picture querman · May 8, 2012 · Viewed 9.4k times · Source

I have a JTextField and i want to setMargin. But when i set any border, it doesn' t properly work. It' s margin function doesn't work. This is my code;

import java.awt.Color;
import java.awt.Insets;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class ImageField {

public static void main(String[] args) throws IOException {

    JTextField textField = new JTextField();
    textField.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
    textField.setMargin(new Insets(0, 20, 0, 0));
    JOptionPane.showMessageDialog(null, textField, "",
            JOptionPane.PLAIN_MESSAGE);
    }
}

If i commant this line, it works

 //textField.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));

Answer

aleroot picture aleroot · May 8, 2012

Margin have some problem with Border, to work around the problem you can try using a CompoundBorder setting an EmptyBorder as inner border and the desired border (lineBorder in your case) as outer border.

Something like this should work :

Border line = BorderFactory.createLineBorder(Color.DARK_GRAY);
Border empty = new EmptyBorder(0, 20, 0, 0);
CompoundBorder border = new CompoundBorder(line, empty);
textField.setBorder(border);