How to disable a button in java without removing its color

2

I have a button that when clicking it changes color, but if you click it again nothing should happen. But I still can not block this action. I tried this 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 it was disabled.

    
asked by anonymous 22.02.2017 / 14:18

2 answers

0

From what I understand, setEnabled(false) changes the appearance of the button itself, there is no way. But try 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);
        }
    }
}
    
22.02.2017 / 14:23
0

This is because of the LookAndFeel (LAF) because it is the one that defines the styling of all swing components. If you apply LAF Metal , which is a more basic LAF, this problem will not happen.

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

If you want to venture into altering the LAF, you can just add the following line inside the main, before starting the screen:

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

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

    
22.02.2017 / 18:47