如何制作简单扁平风格的JButton?

17

如何使JButton仅显示背景颜色?我不需要其他效果,例如边框、3D外观或悬停高亮显示。

提前感谢。


谢谢您的回答。当我点击按钮时,仍然会出现高亮显示。其他方面都没问题。有什么办法可以停止它的高亮显示吗? - c0d3x
你可以通过设置自定义的 ButtonUI 来控制它。 - McDowell
6个回答

33
我通常会做类似这样的事情:
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setContentAreaFilled(false);

setContentAreaFilled(false) 是我缺少的最后一步,使按钮真正平坦而没有边框 - 谢谢! - rob

13

只需设置颜色和边框:

private static JButton createSimpleButton(String text) {
  JButton button = new JButton(text);
  button.setForeground(Color.BLACK);
  button.setBackground(Color.WHITE);
  Border line = new LineBorder(Color.BLACK);
  Border margin = new EmptyBorder(5, 15, 5, 15);
  Border compound = new CompoundBorder(line, margin);
  button.setBorder(compound);
  return button;
}

使用setOpaque(false);使背景透明。


2
怎么样?
yourButton.setBorder(null);

?


1

首先,将您的外观设置为酷炫的样式,比如“金属”。

try
{
    for (UIManager.LookAndFeelInfo lnf : 
        UIManager.getInstalledLookAndFeels()) {
        if ("Metal".equals(lnf.getName())) {
            UIManager.setLookAndFeel(lnf.getClassName());
            break;
        }
    }
} catch (Exception e) { /* Lazy handling this >.> */ }

然后做这样的事情:
my_jbutton.setBackground(new Color(240,240,241);

如果您的按钮颜色恰好等于摆动控件颜色(240,240,240),Windows将为按钮应用类似Windows的按钮样式,否则,按钮将采用简单的平面样式。

1
你可能想要使用带有MouseListener的JLabel,除非你必须以某种方式使用JButton或ActionListener。

这个可以解决问题,但会影响键盘焦点/可访问性。 - McDowell

0

我认为你可以这样做

JButton button = new JButton("Click Me!!");
button.setBorderPainted(false);
button.setBackground(new Color());// inside the brackets your rgb color value like 255,255,255
button.setFocusPainted(false);

你可以使用颜色选择器获取RGB代码(只需搜索颜色选择器)


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