开发者

How can I resize the background of a JLabel or apply top and bottom borders only?

I have something that looks like this:

How can I resize the background of a JLabel or apply top and bottom borders only?

As you can see, "Blambo" is a JLabel with an opaque, red background. The label sits on top of a little grey bar that has a single pixel blackish border all the way around it. I'd like my red warning to match the bar it's sitting on more nicely, i.e. I either need to make it two pixels shorter and move it down a pixel or I need to apply the same single pixel border to the top and bottom only. Of those two, the first is probably preferable as this piece of code is shared with other labels.

The code in question:

bgColor = Color.red;
textColor = Color.white;
setBackground(bgColor);
setOpaque(true);
// This line merely adds some padding on the left
setBor开发者_如何学运维der(Global.border_left_margin);   
setForeground(textColor);
setFont(font);
super.paint(g);

That border is defined thusly:

public static Border border_left_margin = new EmptyBorder(0,6,0,0);


You can create a new border for the label like this :

EDIT: after seeing your comment in another answer i created a compound border which gives you what you want.

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;

/**
 * @author Savvas Dalkitsis
 */
public class Test1 {

    public static void main(String[] args) {
        JFrame f = new JFrame("Test");
        JLabel c = new JLabel("Hello");
        Border b = BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(2, 0, 2, 0, Color.black),
                BorderFactory.createEmptyBorder(0, 100, 0, 0));
        c.setBorder(b);
        f.getContentPane().add(c);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

}


Without seeing your code, it's hard to know what you already know or have tried.

You explicitly set the border of a component like so:

myLabel.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.BLACK));

Now, JLabels are rather complicated beasts, with a lot of code for measuring its (optional) icon, and planning its layout around lots of general cases. You might be better off subclassing JComponent to write your own, very simple label.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜