Draw a JButton to look like a JLabel (or at least without the button edge?)

Electrons_Ahoy picture Electrons_Ahoy · Jun 11, 2010 · Viewed 11.5k times · Source

I've got a JButton that for various reasons I want to act like a button, but look like a JLabel. It doesn't actually have to be a JLabel under the hood, I just don't want the raised button edge to show up.

Is there an easy way to turn off the "button look" for JButtons but keep all the button functionality?

I could build some kind of composed subclass hyperbutton that delegated to a jlabel for display purposes, but I'm really hoping there's something along the lines of button.lookLikeAButton(false).

Answer

Avrom picture Avrom · Jun 11, 2010

You will want to do the following:

        setFocusPainted(false);
        setMargin(new Insets(0, 0, 0, 0));
        setContentAreaFilled(false);
        setBorderPainted(false);
        setOpaque(false);

You may want to exclude setFocusPainted(false) if you want it to actually paint the focus (e.g. dotted line border on Windows look and feel).

I have used the above code in cases where I have wanted an "icon only" button.