简体   繁体   English

如何向 jtextfield 添加填充

[英]How can I add padding to a jtextfield

How can I add some padding to a jtextfield?如何向 jtextfield 添加一些填充? I've tried tf.setMargin(new Insets(5,5,5,5));我试过tf.setMargin(new Insets(5,5,5,5)); which doesn't have any effect.这没有任何影响。

The problem you are having is that the UI is setting its own border on the text field, overriding the margin you set.您遇到的问题是 UI 在文本字段上设置了自己的边框,覆盖了您设置的边距。 You can see a warning to this effect in the javadoc of setMargin() .您可以在setMargin()的 javadoc 中看到对此效果的警告。

The solution is to let the UI set a border, then squeeze in another border of your own:解决办法是让UI设置一个边框,然后再挤进你自己的另一个边框:

field.setBorder(BorderFactory.createCompoundBorder(
        field.getBorder(), 
        BorderFactory.createEmptyBorder(5, 5, 5, 5)));

你看看CompoundBorder ,在那里你可以设置LineBorder(Color.gray, 1)并使用

EmptyBorder(5, 5, 5, 5)

最简单的方法是使用BorderFactory

field.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

I know this is years too late, but actually, if you want a consistent look and feel in Java, you should be editing the UI so every text field you create doesn't need its own special code.我知道这已经晚了很多年,但实际上,如果您想要在 Java 中获得一致的外观和感觉,您应该编辑 UI,这样您创建的每个文本字段都不需要自己的特殊代码。 So, taking from Russel Zahniser's example above:因此,从上面的 Russel Zahniser 示例中获取:

Border tfBorder = UIManager.getBorder("TextField.border");
Border newBorder = BorderFactory.createCompoundBorder(tfBorder, 
        BorderFactory.createEmptyBorder(5, 5, 5, 5)));

UIManager.setBorder("TextField.border", newBorder);
yourTextFeildVariable.setBorder(BorderFactory.createCompoundBorder(yourTextFeildVariable.getBorder(), BorderFactory.createEmptyBorder(0, 5, 0, 0)));

This is working 100%这是工作 100%

在此处输入图片说明

您可以将此应用于已创建的带有边框的文本框

jTextField1.setBorder(BorderFactory.createCompoundBorder(jTextField1.getBorder(), BorderFactory.createEmptyBorder(6, 6, 6, 6)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM