How to change the color of a button?

Asked

Viewed 3,390 times

0

I’m doing some experiments to get to know the Netbeans IDE better and I got this one button coloring question.

Right-clicking on any jButton and selecting Properties, configure the item background in the green color, for example, but only the edge of the button gets the color selected.

jButton antes da alteração
JButton before the change in Properties

jButton depois da alteração
JButton after the change in Properties

I already changed the LAF to Windows and returned to Nimbus (default) and nothing different happens.

You can change the fill color of a button?

  • I’ve already answered your question, but if you don’t provide one [mcve] there is no way I can verify the problem. The solution below is functional.

  • Only now have I seen your comment. I’m using the Netbeans GUI editor and put the screenshots of the small screen to demonstrate what’s going on, as Netbeans generates a lot of code that would be confusing to post here. This is my minimum example.

1 answer

1


To change the color, just use setBackground() passing the desired color through the class Color, using your constants or creating custom colors:

botao.setBackground(Color.red);

However, most of the Lookandfeels(LAF) already has default color settings and even changing the above method, does not allow changing correctly in some cases. To solve this, you need to "remove" this stylization of the component, through the methods below:

    botao.setContentAreaFilled(false);
    botao.setOpaque(true);
    botao.setBackground(Color.RED);

Upshot:

inserir a descrição da imagem aqui

Obs.: By doing this, you are giving up all the stylizations made by LAF, and not only the background and foreground colors.

  • I found this sequence of settings in Button Properties. As I am using the Netbeans GUI editor, I only selected/de-selected the items that you passed and worked. I just didn’t know about the side effect you mentioned

  • @Anonreports can’t program an interface without tampering with the code. It is recommended that you learn how to handle the code, otherwise you will waste time creating interface and then solving problems with the code generated by the ide, which is immense and confusing.

  • Just change the properties of the item in its properties! Netbeans does not allow your generated code to be changed, few snippets are free for editing, but the bulk (when working with GUI) is protected. Don’t bother, I deleted my account! o/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.