我想在 JTextField 周围使用 TitledBorder,而不占用太多垂直空间。
在顶部,它为标题字体应用了比需要的更多的间距。另外,底部有 4 个像素我无法使用。
这仅发生在 Windows 上;在 Mac OSX 上,下面的示例看起来不错,而在 W10 上,JTextField 内容被严重裁剪。
我可以以任何方式减少这个吗?
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class MoreSpace {
static public void main(String args[]) {
EmptyBorder eb = new EmptyBorder(0, 0, 0, 0);
TitledBorder tb = new TitledBorder(eb, "Title");
Font font = new Font("dialog", Font.BOLD, 10);
tb.setTitleFont(font);
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(300,26));
textField.setBorder(tb);
textField.setText("I cant breathe in here");
JOptionPane.showMessageDialog(null, textField, "",JOptionPane.PLAIN_MESSAGE);
}
}
最佳答案
创建自定义 TitledBorder 类(来自 javax.swing.border 包)并根据需要减少最大 EDGE_SPACING。
//边框和组件边缘之间的空间 静态 protected 最终 int EDGE_SPACING = 2;
这意味着 TitledBorder 默认情况下上下 2 个像素作为填充。这应该可以解释您所看到的 4 个像素。
将 EDGE_SPACING 设置为 0 将满足您的要求。 :)
关于Java - TitledBorder 占用太多垂直空间(仅限 Windows),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134308/