Mario Ishac
Mario Ishac

Reputation: 5877

Getting pixels between border of TextArea and text inside

enter image description here

I wish to obtain and modify the number of pixels between the text contained inside the text area and the border of the text area. To provide a more descriptive visual:

enter image description here

where the length of the blue line is what I desired. When I received both the padding and margins of the text area in my application, I got 0px. I assume that this is the padding/margin of the TextArea relative to the outside, not the inside relative to the Ttext area.

Many thanks.

Upvotes: 2

Views: 954

Answers (1)

Ivan86
Ivan86

Reputation: 5708

In java to set the insets of a textarea you can use setMargin().

public void setMargin(Insets m)

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.

Parameters: m - the space between the border and the text

for example:

JTextArea txtArea = new JTextArea("Hello world!");
txtArea.setMargin( new Insets(15,15,15,15) );

more on insets and setMargin().

Or another approach would be to add a compound border and then setting the insets on it like this:

 JTextArea txtArea = new JTextArea("Hello world!");
 Border border = BorderFactory.createLineBorder(Color.RED);
 txtArea.setBorder(BorderFactory.createCompoundBorder(
       border, BorderFactory.createEmptyBorder(15, 15, 15, 15))
 );

see this answer.

Upvotes: 1

Related Questions