mlecoz
mlecoz

Reputation: 449

color of JButton

After reviewing many previous StackOverflow posts, I am still unable to get my JButton to be black instead of the default color. Here is what my button looks like:

This is what my button looks like.

And here's my code:

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

}

By the way, when I change setContentAreaFilled to true, it makes no difference.

I know that the function is indeed being called, because the location and font info for my button is working just fine.

Any assistance would be much appreciated! Thanks!

Upvotes: 0

Views: 86

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

A JButton is made of a series of layers, including the content, border and focus layers. Depending on what you're trying to do, you may need to remove all of them, for example...

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

    }

}

I'd also strongly encourage you to consider making use of an appropriate layout manager and using the properties of it and the JButton to generate the desired padding you need, these will work together with the font metrics, which tend to be different between systems, to generate an appropriate size for the button

Upvotes: 1

Related Questions