在JButton上放置ImageIcon时出现边框问题

时间:2016-06-07 11:02:57

标签: java swing jbutton imageicon

我正在创建如下图像按钮

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Insets;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Demo {

private JFrame mainFrame;

static public Color BGCOLOUR1 = new Color(240, 240, 240);

public Demo() {

    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        ex.printStackTrace();
    } 

    mainFrame = new JFrame("DEMO");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setBackground(BGCOLOUR1);
    mainFrame.setSize(300, 300);
    mainFrame.setLayout(new BorderLayout());


    JPanel smButtonContainer = new JPanel();
    smButtonContainer.setLayout(new FlowLayout());
    smButtonContainer.setOpaque(true);
    smButtonContainer.setBackground(Color.WHITE);
    smButtonContainer.setBorder(BorderFactory.createEmptyBorder(25, 10, 5, 0));

    ImageIcon emailLogo = new ImageIcon(getClass().getResource("/resources/email.png"));
    JButton emailButton = new JButton(emailLogo);
    emailButton.setBorder(null);
    emailButton.setBorderPainted(false);
    emailButton.setBackground(Color.WHITE);
    emailButton.setMargin(new Insets(0, 0, 0, 0));

    smButtonContainer.add(emailButton);

    mainFrame.add(smButtonContainer);


}

public static void main(String[] args) {
    Demo demo = new Demo();
    demo.showUI();
}

private void showUI() {
    mainFrame.setVisible(true);
}

}

在我的开发机器(Fedora 23 / KDE)上看起来很不错:

enter image description here

但是,当我在Windows 7计算机上运行应用程序时,按钮看起来像是:

enter image description here

为什么会发生这种情况?我怎么能阻止这个?

编辑:更新了示例。

1 个答案:

答案 0 :(得分:1)

您还需要添加:

emailButton.setFocusPainted(false);

在Windows上,绘制一个虚线矩形以指示按钮具有焦点。