JButton去掉按钮字周围的虚线框

JButton去掉按钮字周围的虚线框

系统:Win10
JDK:1.8.0_121
IDEA:2017.3.2

1.问题描述

在测试Swing项目的时候,发现每次点击按钮,按钮上面字的周围都会出现一个线框,现在不想该线框显示。
如下图所示:
在这里插入图片描述

2.解决办法

使用类 AbstractButton 下的 setFocusPainted 方法,将绘制焦点状态设置为false,则不会在获取到焦点的时候,绘制这个框框了

// 设置 paintFocus 属性,设置为false 则不会绘制焦点状态
button.setFocusPainted(false);

setFocusPainted 方法的源码

/**
     * Sets the <code>paintFocus</code> property, which must
     * be <code>true</code> for the focus state to be painted.
     * The default value for the <code>paintFocus</code> property
     * is <code>true</code>.
     * Some look and feels might not paint focus state;
     * they will ignore this property.
     *
     * @param b if <code>true</code>, the focus state should be painted
     * @see #isFocusPainted
     * @beaninfo
     *        bound: true
     *    attribute: visualUpdate true
     *  description: Whether focus should be painted
     */
    public void setFocusPainted(boolean b) {
    
    
        boolean oldValue = paintFocus;
        paintFocus = b;
        firePropertyChange(FOCUS_PAINTED_CHANGED_PROPERTY, oldValue, paintFocus);
        if (b != oldValue && isFocusOwner()) {
    
    
            revalidate();
            repaint();
        }
    }

3.代码示例

/*
 测试按钮不绘制焦点状态
 */
public class JButtonDemo {
    
    
    public static void main(String[] args) {
    
    
        JFrame frame = new JFrame("测试绘制焦点状态");
        frame.setLayout(null);
        JPanel panel = new JPanel();
        panel.setBounds(140,100,100,40);
        frame.setSize(new Dimension(400, 300));
        JButton button = new JButton("普通按钮");
        // 设置 paintFocus 属性,设置为false 则不会绘制焦点状态
        button.setFocusPainted(false);

        // 添加按钮
        panel.add(button);
        frame.add(panel);
        // 获取焦点
        frame.setFocusable(true);
        // 居中显示
        frame.setLocationRelativeTo(null);
        // 设置可见
        frame.setVisible(true);
    }
}

4.效果演示

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_35132089/article/details/112287810