我想在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);
}
}
答案 0 :(得分:3)
创建一个自定义的TitledBorder类(来自javax.swing.border包),并根据需要减少最大EDGE_SPACING。
//边界和组件边缘之间的空间 静态保护的最终int EDGE_SPACING = 2;
这意味着默认情况下,TitledBorder的上下两个像素为填充。这应该可以解释您看到的4个像素。
将EDGE_SPACING设置为0将完成您想要的操作。 :)