我尝试使用MatteBorder
,以便在JTextField
的开头显示一个图标(类似于在文本字段中显示的搜索图标)。
这是我当前的实现:
JTextField textField = new JTextField("Filter", 8);
textField.setPreferredSize(new Dimension(getPreferredSize().width, 24));
Border outer = textField.getBorder();
// ugly workaround
Border padding = BorderFactory.createEmptyBorder(2, 2, 2, 2);
Border search = new MatteBorder(0, 16, 0, 0, icon);
textField.setBorder(new CompoundBorder(new CompoundBorder(outer, padding), search));
该图标是一个 16x16px 的图标,周围没有空格。文本字段高 24 像素。我引入了一个填充边框,以便在图标周围有一些空白(否则它将显示完整的图标及其下方图标的前 4 像素)。我的问题是图标右侧(用户输入文本的位置)没有空格。
问题:有没有办法让图像周围有一定数量的空白,这样图像就不会平铺?在将图标添加到 MatteBorder
之前,我可以以某种方式在图标周围添加“填充”吗?
附注我知道我可以在图像文件周围添加空格,但它用于其他不应在其周围有任何空格的情况。
最佳答案
由于 MatteBorder 总是平铺图标,因此我不会使用它。我只想写一个自定义边框:
static void updateBorder(JTextField textField,
Icon icon) {
Border iconBorder = new AbstractBorder() {
private static final long serialVersionUID = 1;
@Override
public Insets getBorderInsets(Component c,
Insets insets)
{
insets.left = icon.getIconWidth() + 4;
insets.right = insets.top = insets.bottom = 0;
return insets;
}
@Override
public void paintBorder(Component c,
Graphics g,
int x,
int y,
int width,
int height)
{
icon.paintIcon(c, g,
x, y + (height - icon.getIconHeight()) / 2);
}
};
Border oldBorder = textField.getBorder();
// Inside text field's original border, place icon border
// with a little empty space around it.
textField.setBorder(BorderFactory.createCompoundBorder(
oldBorder,
BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(2, 2, 2, 2),
iconBorder)));
}
关于java - 如何在 matteborder 中的图标周围添加空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50875430/