2017-04-09 86 views
0

在回顧了很多以前的StackOverflow帖子之後,我仍然無法讓我的JButton變成黑色而不是默認顏色。這裏是我的按鈕看起來像:JButton的顏色

This is what my button looks like.

這裏是我的代碼:

public void setStartButton() { 

    JPanel panel = this.jPanel1; 
    panel.setLayout(null); 

    JButton button = new JButton("START"); 

    // size and location of start button 
    int res = java.awt.Toolkit.getDefaultToolkit().getScreenResolution(); 
    int length = (int) Math.floor(10.0*res/25.4); // side lengths of square button 
    int offset = length/2; // because button should be centered...but its x and y location are given by its upper left hand corner 
    button.setBounds(centerX-offset, centerY-offset, length, length); 

    // color of start button 
    button.setBackground(BLACK); 
    button.setOpaque(true); 
    button.setContentAreaFilled(false); 

    // font 
    button.setFont(new Font("Arial", Font.PLAIN, 8)); 

    button.setVisible(true); 
    panel.add(button); 

} 

順便說一句,當我改變setContentAreaFilledtrue,這都沒有區別。

我知道該函數確實被調用,因爲我的按鈕的位置和字體信息工作得很好。

任何援助將不勝感激!謝謝!

+0

將BLACK更改爲Color.BLACK。還要確保你'import java.awt.Color' – JackVanier

+0

那麼,我已經導入了'import static java.awt.Color.BLACK;',這樣應該可以工作吧? – mlecoz

+0

並認真考慮使用適當的佈局管理器 – MadProgrammer

回答

1

A JButton由一系列層組成,包括content,borderfocus層。這取決於你想做什麼,你可能需要將它們全部刪除,例如...

Button

public class TestPane extends JPanel { 

    public TestPane() { 
     setLayout(new GridBagLayout()); 
     setStartButton(); 
    } 

    public void setStartButton() { 

     JButton button = new JButton("START"); 
     button.setMargin(new Insets(20, 20, 20, 20)); 

     // color of start button 
     button.setOpaque(true); 
     button.setContentAreaFilled(true); 
     button.setBorderPainted(false); 
     button.setFocusPainted(false); 
     button.setBackground(BLACK); 
     button.setForeground(WHITE); 

     // font 
     button.setFont(new Font("Arial", Font.PLAIN, 8)); 
     add(button); 

    } 

} 

我還強烈建議您考慮做適當的使用佈局管理器,並使用它的屬性和JButton來生成所需的填充,這些將與字體度量一起工作,這些字體度量在系統之間傾向於不同,爲按鈕生成適當的大小

+0

非常感謝!這工作! – mlecoz