在Swing中的组件文本下方绘制边框

时间:2016-01-27 19:38:37

标签: java swing graphics border

我创建了一个自定义边框类,我在其中填充一个矩形作为组件的背景。请注意,此边框将来会有更复杂的形状,而不仅仅是一个简单的矩形。

当我将边框添加到组件时,组件的文本将显示在边框后面并使文本不可读。 (结果如下图所示。)

有没有办法在文本下方绘制边框?

http://i.stack.imgur.com/Y9ehY.png

我的边境班:

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()的彩色方块是禁止的。

2 个答案:

答案 0 :(得分:3)

参见this answer,其中解释了绘画是如何完成的。在绘制标签文本后绘制边框。

你到底想要做什么?你的边框绘画代码没有意义。您正在尝试填充等于组件宽度/高度+ 20像素的矩形,这意味着您尝试绘制的区域大于组件。

如果您只是想在标签上绘制背景,那么您可以使用:

Template.Example.events({
  'click #example': function(event, template) {
    instance = template; // or = Template.instance();
    instance_reactive_data_context = template.currentData(); // or = Template.currentData();
    instance_nonreactive_data_context = ???
    event_data_context = event.currentTarget;
});

Template.Example.helpers({
  example: function() {
    instance = Template.instance();
    instance_reactive_data_context = this; // or = Template.currentData();
    instance_nonreactive_data_context = ???
  }
});

Template.Example.onCreated(function () {
  instance = this;
  instance_reactive_data_context = this.currentData();
  instance_nonreactive_data_context = this.data;
});

编辑:下面评论部分中链接的{{3}}中的代码解决了问题。

答案 1 :(得分:1)

您可以随时使用JLabel l = new JLabel("foo"); l.setBackground(Color.GRAY); l.setOpaque(true); 。 但是,如果由于某种原因不能使用它,你可以这样做:

opencv_createsamples