Java – How to resize the background of a JLabel or apply top and bottom borders only

javajlabelswing

I have something that looks like this:

alt text

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
setBorder(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);

Best Solution

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);
    }

}