2009-12-03 21 views
11

什麼是最簡單的方法來使JButton只顯示背景顏色?我不需要任何其他效果如邊框,3D外觀或懸停高亮。如何用簡單的平面樣式製作JButton?

在此先感謝。

+0

感謝您的回答。當我點擊按鈕時,仍然有突出顯示。剩下的就好了。任何想法如何阻止它突出顯示? – c0d3x 2009-12-03 10:59:23

+0

你可以通過設置一個自定義的'ButtonUI'來控制它。 – McDowell 2009-12-03 11:35:50

回答

2

如何

yourButton.setBorder(null); 

12

只需設置的顏色和邊框:

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);,使背景透明。

1

您可能希望使用帶有MouseListener的JLabel,除非您以某種方式使用JButton或ActionListener。

+0

這會起作用,但會影響鍵盤焦點/可訪問性。 – McDowell 2009-12-03 13:42:00

23

我不知道如果我錯過了點... 但我平時somtehing這樣的:

button.setBorderPainted(false); 
button.setFocusPainted(false); 
button.setContentAreaFilled(false); 
+0

setContentAreaFilled(false)是我錯過了讓按鈕真正平坦無邊框的最後一件事 - 謝謝! – rob 2014-01-06 20:02:11

+0

它工作的很好,現在我該如何在JButton上添加下劃線? – 2015-03-11 12:06:19

0

首先,設置你的外觀和感覺一些很酷的東西,像「金屬」。

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); 

如果您的按鈕的顏色恰好等於擺動控制顏色(240240240),Windows將應用Windows般的按鈕樣式的按鈕,否則,該按鈕呈現簡單的平面樣式。