Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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).

like image 938
Electrons_Ahoy Avatar asked Jun 11 '10 18:06

Electrons_Ahoy


People also ask

How do I create a JButton image?

To add icon to a button, use the Icon class, which will allow you to add an image to the button. Icon icon = new ImageIcon("E:\editicon. PNG"); JButton button7 = new JButton(icon);

What is different between JButton and button?

A button generates an action event when it is pressed. The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed.


2 Answers

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.

like image 72
Avrom Avatar answered Oct 30 '22 20:10

Avrom


Set the background color to transparent, and the border to an EmptyBorder instance.

E.g.

   JButton button = new JButton();
   button.setBackground(null);
   button.setOpaque(false);
   button.setBorder(new EmptyBorder());

The text will still move up and down as you click the button, and the button can still be "armed" by clicking, holding, and "disarmed" by moving the mouse out of the button area.

If you don't want this behaviour, then you probably don't want to use a button, and use a real label instead.

like image 20
mdma Avatar answered Oct 30 '22 21:10

mdma