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,?
– user28595
Another thing, Frame has not been "disabled". And only visible or not visible.
– user28595
@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.
– JavaTech