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

China☆狼群 提交于 2019-11-27 13:45:11

问题


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


回答1:


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.




回答2:


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.




回答3:


button.setBorderPainted( false );
button.setContentAreaFilled( false ); // ?



回答4:


 setContentAreaFilled(false);
 setBorderPainted(false);
 setOpaque(false);

This three lines do the trick.




回答5:


Might it actually be easier just to add a mouse listener to a JLabel? You could adjust the colors on mousePressed and mouseReleased, and do your action processing on mouseClicked?



来源:https://stackoverflow.com/questions/3025320/draw-a-jbutton-to-look-like-a-jlabel-or-at-least-without-the-button-edge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!