JTextField margin doesnt work with border
Asked Answered
Y

2

9

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));
Yuma answered 8/5, 2012 at 10:27 Comment(1)
I love this Compound Border thingy, when it comes to settings the Borders, since you can specify one Empty Border with it and it gives almost the same impression as setting one's margin thingy :-)Centum
T
21

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);
Threadgill answered 8/5, 2012 at 10:38 Comment(0)
S
6

Read it from the JavaDoc.

Sets margin space between the text component's border and its text. The text component's default Border object will use this value to create the proper margin. However, if a non-default border is set on the text component, it is that Border object's responsibility to create the appropriate margin space (else this property will effectively be ignored). This causes a redraw of the component. A PropertyChange event ("margin") is sent to all listeners.

You are probably looking for a compound border:

BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.DARK_GRAY),
                BorderFactory.createEmptyBorder(0, 20, 0, 0));
Saurian answered 8/5, 2012 at 10:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.