ononononon
ononononon

Reputation: 1083

JTextField margins

I want to add margin to a TextField.

Current effect / Desired Effect:

Current Effect

Desired Effect with 10px left margin

As you can see, i want to add 10px left margin to JTextField.

Current code:

textField_host.setBorder(
    BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(Color.DARK_GRAY),
        BorderFactory.createEmptyBorder(0, 20, 0, 0 )
    )
);

How to achieve that? Thank you.

Upvotes: 2

Views: 1587

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

So, if you have a look at the JavaDocs for BorderFactory.createCompoundBorder you will see that parameters are in outside, inside order...

public static CompoundBorder createCompoundBorder(Border outsideBorder,
                              Border insideBorder)

Which means you should probably be something more like...

textField_host.setBorder(
    BorderFactory.createCompoundBorder(
        BorderFactory.creat‌​eEmptyBorder(0, 20, 0, 0 ), 
        textField_host.getBorder()
    )
);

The other solution is to use a layout manager which gives you more control over the layout, like GridBagLayout

Upvotes: 4

Arnaud
Arnaud

Reputation: 17524

You can add a Box.createHorizontalStrut(10) to the left of your textField.

Upvotes: 1

Related Questions