tags:

views:

90

answers:

2

I've got sort of weird issue that I can't seem to figure out. 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.

Thanks in advance for the help.

Edit: 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);
A: 

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.

Jonathan Feinberg
That's actually pretty close. Is there anyway to have that border and preserve my left side padding?
Morinar
You need a compound border. See my answer for details.
Savvas Dalkitsis
A: 

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

}
Savvas Dalkitsis
That is spot on exactly what I was looking for. Thanks!
Morinar