禁用 JButton 焦点边框

问题描述 投票:0回答:6

我在 Java 中遇到 JButton 问题。基本上,我想禁用按钮的边框(按钮添加到 JDesktopPane )。

这是我的代码:

 JButton j = new JButton("BUTTON");
 j.setIcon(icon1); //icon1 : icon//
 j.setFocusable(true);
 j.setContentAreaFilled(false);
 j.setBounds(90, 20, 130, 30);
 dtp.add(j); //dtp : JDesktopPane//

它可以让边框消失,如下图所示:

enter image description here

但是当我的鼠标单击(未移动)到按钮时,按钮周围有一个“点”边框,如下所示:

enter image description here

那么,我如何设置按钮,以便当我不在按钮区域周围移动鼠标时,它仍然像第一个图像一样设置,但是当我移动鼠标时,按钮周围有一个正方形(带有灯光) -蓝色背景)?

java swing jbutton
6个回答
120
投票

那不是边界。这是焦点。您可以使用以下方法删除它:

jButton1.setFocusPainted(false);

11
投票

这可能是旧线程,但我解决了我的问题

button.setFocusable(false)

希望它对那些仍在寻找答案的人有所帮助。 干杯。


4
投票

经过挖掘,我想出了更好的解决方案。这也是 Windows 上的 GTK 应用程序中常见的 UI 错误,GIMP 就是其中之一。这让我非常烦恼,所以我想找到一个更好的全局修复方法,而不是手动在每个控件上设置它。

解决方法将所有不应出现的常见控件的焦点颜色设置为透明。我在 Visual Studio 中使用 Windows 窗体进行了广泛的测试。即使在聚焦时,工具栏按钮和切换按钮也不应该有虚线边框。工具栏应该是 setFocusable(false);默认情况下,就像在 Windows 中一样。所有其他控件都应具有与 Swing 中一样的虚线边框,但仅在焦点循环时才有效。

        // Removes the dotted border around controls which is not consistent with Windows
        UIManager.put("Button.focus", new ColorUIResource(new Color(0, 0, 0, 0)));
        UIManager.put("ToggleButton.focus", new ColorUIResource(new Color(0, 0, 0, 0)));

        // ways to remove it from other controls...
        UIManager.put("CheckBox.focus", new ColorUIResource(new Color(0, 0, 0, 0)));
        UIManager.put("TabbedPane.focus", new ColorUIResource(new Color(0, 0, 0, 0)));
        UIManager.put("RadioButton.focus", new ColorUIResource(new Color(0, 0, 0, 0)));
        UIManager.put("Slider.focus", new ColorUIResource(new Color(0, 0, 0, 0)));

        // figure out combobox
        UIManager.put("ComboBox.focus", new ColorUIResource(new Color(0, 0, 0, 0)));

1
投票

我不认为像往常一样这样做是个好主意。如果没有,它不会在不同平台(Mac 和 Linux)中显示类似的内容,以防您计划在不同平台上显示此按钮。 出于所有实际目的,

JButton
应满足您当前的要求。

考虑使用具有类似按钮行为(带有操作侦听器)的扩展

button.setFocusPainted(false);

以避免行为差异。

    


0
投票
删除边框

或者也许是这个

JLabel



0
投票
© www.soinside.com 2019 - 2024. All rights reserved.