我创建了一个自定义边框类,在其中填充了一个矩形以用作组件的背景。请注意,此边框将来会具有更复杂的形状,而不仅仅是一个简单的矩形。
当我将边框添加到组件时,组件的文本将出现在边框后面,并使文本不可读。(结果如下图所示。)
有没有办法在文本下方绘制边框?
我的边防课:
public class CustomBorder extends AbstractBorder {
private static final long serialVersionUID = 1L;
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(125, 125, 125, 255));
g2d.fillRect(x - 10, y - 10, width + 20, height + 20);
}
@Override
public Insets getBorderInsets(Component c) {
return super.getBorderInsets(c);
}
@Override
public Insets getBorderInsets(Component c, Insets insets) {
return super.getBorderInsets(c, insets);
}
@Override
public boolean isBorderOpaque() {
return super.isBorderOpaque();
}
}
主要的:
public static void main(String[] args) {
JLabel label = new JLabel("JLabel text");
label.setBorder(new CompoundBorder(new EmptyBorder(50, 20, 20, 20), new CustomBorder()));
JFrame frame = new JFrame("");
frame.setLayout(new FlowLayout());
frame.setSize(200, 200);
frame.add(label);
frame.setVisible(true);
}
编辑:我还应该注意,我将对聊天程序使用此边框,该程序将使用气泡状消息,因此使用setBackground()的彩色正方形是禁止的。
请参阅“仔细研究绘画机制”,它解释了绘画的完成方式。在绘制标签文本之后,将绘制边框。
您到底想做什么?您的边框绘画代码没有意义。您试图填充等于组件宽度/高度+ 20像素的矩形,这意味着您试图绘制大于组件的区域。
如果您只是想在标签上绘制背景,则可以使用:
label.setOpaque( true );
label.setBackground(...);
编辑:在下面的评论部分链接的此答案中的代码解决了该问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句