How to disable a java button without removing its color

Asked

Viewed 700 times

2

I have a button that when you click it changes color, but if you click it again nothing should happen. However, I still can’t block this action. I tried that code:

private void Button1_1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    if(TextoJogador.getText().equals("Jogador 1")){
        Button1_1.setBackground(Color.CYAN);
        TextoJogador.setText("Jogador 2");
        play(sound);

    }else{
        Button1_1.setBackground(Color.GREEN);
        TextoJogador.setText("Jogador 1");
        play(sound);
    }
    Button1_1.setEnable(false); //essa parte que faz o button perder a cor
}

but the button loses the color that was selected when disabled.

  • What is the initial color of the button (before any click)?

  • No color. it only gets a color after the first click, that’s a game of old.

2 answers

0


From what I understand the setEnabled(false) changes the appearance of the button even, there is no way. But try it like this:

private void Button1_1ActionPerformed(java.awt.event.ActionEvent evt) {
    if (Button1_1.getBackground() != Color.CYAN && Button1_1.getBackground() != Color.GREEN) {
        if(TextoJogador.getText().equals("Jogador 1")){
            Button1_1.setBackground(Color.CYAN);
            TextoJogador.setText("Jogador 2");
            play(sound);

        }else{
            Button1_1.setBackground(Color.GREEN);
            TextoJogador.setText("Jogador 1");
            play(sound);
        }
    }
}
  • I shall supplement the question

  • Make sure you answer it now

  • Perfect bro, hadn’t thought of it :) Thanks!

  • Fine, just accept the answer then by clicking on the left and voting +1. Thank you.

0

This is because of Lookandfeel(LAF), because it is he who defines the stylizations of all the components of swing. If you apply the LAF Metal, which is a more basic LAF, this problem will not happen.

However, I imagine you are using Nimbus, which is the default LAF for projects created by netbeans, yet you can change it directly, but the other answer turns out to be simpler and more workable, without having to leave the appearance of the most basic application.

If you want to venture into changing the LAF, you can add only the line below inside the main, before starting the screen:

UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");

With that, the setEnabled(false) does not affect the background you initially changed from the button, but as a consequence of being a basic theme, your application looks more rudimentary when compared to Nimbus.

Browser other questions tagged

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