Change label color according to screen state

Asked

Viewed 1,282 times

2

I’m having trouble changing the color of a label’s content according to the state of my screen (enabled/disabled).

I wonder how I do so I can make him change the color.

I made a very simple example (without worrying about organization best practices and etc)

Simplified example of code:

package cor;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class MudaCor extends JFrame implements ActionListener
{
    public final int DESABILITADA = 0;
    public final int HABILITADA = 1;
    public int estadoTela = DESABILITADA;

    public JPanel jpBotoes = new JPanel();
    JTextField tx1 = new JTextField();
    JTextField tx2 = new JTextField();

    private JButton botao01 = new JButton("Habilita");
    private JButton botao02 = new JButton("Desabilita");

    private String conteudo = "Teste de cor";

    public MudaCor()
    {
        setTitle("Tela de teste");
        setSize(400, 300);      
        add(posicaoComponentes());        
        habilitaComp(false);        
        estilo(conteudo);//metodo estilo        
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }    

    public String  estilo(String estilo)
    {
        String x = "<html><font color=#4a2d56> <b> Teste de cor </b> </font></html>"; //roxo
        String y = "<html><font color=#225218> <b> Teste de cor </b> </font></html>";//verde

        if(estadoTela != DESABILITADA)
        {
            return conteudo = x;
        }

        else
        {
            return conteudo = y;
        }        
    }       

    public JComponent posicaoComponentes()
    {
        JPanel painel = new JPanel();
        painel.setLayout(null);
        JLabel label = new JLabel(estilo(conteudo));        
        painel.add(label);
        label.setBounds(170, 150, 100, 25);        
        painel.add(tx1);
        tx1.setBounds(130, 30, 150, 22);                            
        painel.add(tx2);       
        tx2.setBounds(130, 70, 150, 22);

        getContentPane().add("South", jpBotoes);        
        jpBotoes.setLayout(new GridLayout(1, 2));      
        adicionaBotao(botao01);
        adicionaBotao(botao02);

        return painel;        
    }

    private void adicionaBotao(JButton botao) 
    {
        jpBotoes.add(botao);
        botao.addActionListener(this);
    }

    public void habilitaComp(boolean status)
    {
        if(estadoTela == DESABILITADA)
        {
            tx1.setEnabled(status);
            tx2.setEnabled(status);
        }

        else
        {
            tx1.setEnabled(status);
            tx2.setEnabled(status);
        }
    }

    @Override
    public void actionPerformed(ActionEvent ae)
    {

        if (ae.getSource() == botao01) 
        {            
            habilitaComp(true);
        } 

        else if (ae.getSource() == botao02) 
        {
            habilitaComp(false);
        } 
    }

    public static void main(String[] args) 
    {
        MudaCor cor = new MudaCor();
        cor.setVisible(true);
    }     
}
  • By "change color", you mean change the background color only, or also the font color,?

  • Another thing, Frame has not been "disabled". And only visible or not visible.

  • @diegofm I expressed bad, when I say enabled/disabled, I referred to the components that are inside the frame (in the case of textField), I only want to change the font color inside the label.

1 answer

2


First of all I want to leave two alerts on your code:

Always start the screen inside the Event-Dispatch-Thread, because the swing API is not Thread-Safe, and the whole interface needs to start within this single Thread. In this answer better explains the reason for this and any problems that may occur. This other answer shows some ways to start the application within this thread.

Avoid using absolute layout, the swing API provides several Layouts Managers to facilitate the life of the programmer when creating screens, in addition to making the screen flexible to different sizes of monitors and resolutions, without it being necessary to treat this directly in the code. Absolute layout will break the appearance of your application depending on the monitor where the application is run.


To change the font color of a JLabel, just use the method setForeground(), but even adding this to your code, it never changes the variable estadoTela and the parameter status of the method habilitaComp, which is what you are using to change the status of the component, it is never used.

I made some changes to your code, so that the color is changed according to the boolean value passed in the method habilitaComp, no need to create constant:

public void habilitaComp(boolean status)
{

    tx1.setEnabled(status);
    tx2.setEnabled(status);
    label.setForeground(status ? new Color(74, 45, 86) : Color.GREEN);

}

With this change, the method estilo and the constants you created to control the state are no longer necessary, since it creates unnecessary complexity for something you can do using ternary operation.

  • It worked, thank you very much! And on the layouts, I usually use Gridbaglayout I did so to try to make it simpler, although it really isn’t the right one !

  • @G.Araujo see the edition, the to simplify further, nor need parole.

  • 2

    this condition would suit, it could be used to do something similar, only for a "component" of the Image icon type ? Thus it would be possible to change the path of an image according to the "status" of the components?

  • @G.Araujo clear! in place of the status you put a condition whatever results in boolean, in place of colors, you put the two paths that should be applied, where the right of the : is the path when the condition is true, and the left the path when the condition is false :)

  • thanks, already gave "a light" this explanation, I will try !

  • i did iconeEndereco = new Imageicon(getClass().getResource(status ? "/images/iconAckageDesabilitado.png" : "/images/iconAbaAddress.png"); and had to call the method before adding the components (which I believe is not right), and even then, he only arrow an image, he does not exchange according to the "status".. any hint ?

  • @G.Araujo I don’t understand what you are doing. What I suggested was instead of label.setForeground(status ? new Color(74, 45, 86) : Color.GREEN); you could do label.setIcon(new ImageIcon(status ? <path da imagem para true> : <path da imagem para false>));. If it’s not like that inside habilitaComp, won’t work.

  • i create the iconeAddress object of type Image Icon, because I was trying to do this (change the icons) of a tabbedPane, then I was making tabbedPane.addTab("Addresses", iconeEndereco, fromEnderecos()); I believe label can not be added in tabbedPane, or there’s a way to convert ?

Show 3 more comments

Browser other questions tagged

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