我想在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。
//边框和组件边缘之间的空间static protected final int EDGE_SPACING = 2;
这意味着TitledBorder默认为上下两个像素作为填充。这应该解释你看到的4个像素。
将EDGE_SPACING设置为0可以满足您的需求。 :)