获取 TextArea 边框和内部文本之间的像素

Getting pixels between border of TextArea and text inside

我想获取并修改文本区域内包含的文本与文本区域边框之间的像素数。提供更具描述性的视觉效果:

其中蓝线的长度是我想要的。当我在我的应用程序中收到文本区域的填充和边距时,我得到 0px。我假设这是 TextArea 相对于外部的 padding/margin,而不是相对于 Ttext 区域的内部。

非常感谢。

java中设置一个textareainsets你可以使用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

例如:

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

有关 insets and setMargin() 的更多信息。

或者另一种方法是添加一个 compound border,然后像这样在其上设置 insets

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

参见 this answer