JButton的边框即使将边框设置为EmptyBorder也不会消失

4
我正在Mac上使用Eclipse设计GUI,我想让JButton仅显示我设置的图标。在Mac OS上看起来很好,但是当我将其导出到jar文件并在Windows OS上运行时,JButton看起来像这样:

enter image description here

边框全部是EmptyBorder
我做错了什么?如何让背景中的方块消失?

听起来像是一个外观和感觉的问题。而且可能两个操作系统对你正在使用的文件格式中的透明像素有不同的解释(尽管我认为这似乎不太可能)。你正在使用什么文件格式?此外,如果你能制作一个sscce,它可能会证明有用。 - S.L. Barth
@Xiaofan Wu,请确保JButton的状态是来自Windows还是MAC OS。 - mKorbel
2个回答

10

为了正确回答这个问题,可能需要提供一个SSCCE。无论如何,我相信您希望在JButton实例上调用setContentAreaFilled(false)方法。那应该可以有效地去除“方形区域”。

但是,请注意,在不同的组件和外观基础上调用此函数的确切行为会有所不同。


import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public final class JButtonDemo {
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();             
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JIconButton());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static final class JIconButton extends JButton{
        private static final long serialVersionUID = 7274140930080397481L;

        public JIconButton(){
            super(UIManager.getIcon("OptionPane.informationIcon"));
            setContentAreaFilled(false);
            setFocusPainted(false);
            setBorder(BorderFactory.createEmptyBorder());
        }
    }
}

输入图像描述


1
+1 可以在 com.apple.laf.AquaLookAndFeel 上工作,但是武装和按下的 UI 提示会消失;为了好玩,尝试添加 this.setPressedIcon(UIManager.getIcon("OptionPane.warningIcon")) - trashgod
@mre:setContentAreaFilled(false)可行!但是我没有编写自己的JButton类,我只是像okButton.setContentAreaFilled(false)这样做。它有效! - xiaofan2406

2
1) 无法重现此问题,没有看到您编写的代码很难说。
2) 因为您触及了XxxButtonUI,这是一个与本地操作系统相关的问题,取决于所用的外观。
3) 如果覆盖MetalButtonUI会发生什么?
4) 是否存在透明背景、一些颜色或其他情况,请参考transulcent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接