java 绘制一个 JButton 使其看起来像一个 JLabel(或者至少没有按钮边缘?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3025320/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw a JButton to look like a JLabel (or at least without the button edge?)
提问by Electrons_Ahoy
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.
我有一个 JButton,出于各种原因,我想表现得像一个按钮,但看起来像一个 JLabel。它实际上不必是引擎盖下的 JLabel,我只是不想显示凸起的按钮边缘。
Is there an easy way to turn off the "button look" for JButtons but keep all the button functionality?
有没有一种简单的方法可以关闭 JButton 的“按钮外观”但保留所有按钮功能?
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).
我可以构建某种组合子类超级按钮,将其委托给 jlabel 以用于显示目的,但我真的希望有一些类似button.lookLikeAButton(false).
回答by Avrom
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).
setFocusPainted(false)如果您希望它实际绘制焦点(例如 Windows 外观上的虚线边框),您可能需要排除。
I have used the above code in cases where I have wanted an "icon only" button.
在我想要一个“仅图标”按钮的情况下,我使用了上面的代码。
回答by mdma
Set the background color to transparent, and the border to an EmptyBorder instance.
将背景颜色设置为透明,并将边框设置为 EmptyBorder 实例。
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.
如果您不想要这种行为,那么您可能不想使用按钮,而是使用真正的标签。
回答by camickr
button.setBorderPainted( false );
button.setContentAreaFilled( false ); // ?
回答by Sagar G.
 setContentAreaFilled(false);
 setBorderPainted(false);
 setOpaque(false);
This three lines do the trick.
这三行可以解决问题。
回答by Curtis
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?
将鼠标侦听器添加到 JLabel 实际上可能更容易吗?您可以调整mousePressed 和mouseReleased 的颜色,并在mouseClicked 上进行动作处理?

