Test Foro de elhacker.net SMF 2.1

Programación => Programación General => Java => Mensaje iniciado por: enon en 10 Diciembre 2021, 04:16 AM

Título: Cambiar color JLabel en java
Publicado por: enon en 10 Diciembre 2021, 04:16 AM
Necesito saber una forma de cambiar el color de fondo de una etiqueta, luego de una eleccion de un combobox, ya utilize la opcion del switch, y dentro de esto cambie el color con  background, pero en el programa se me pide que si se selecciona de nuevo tiene que volver a cambiar a otro color, y no se como lo puedo hacer
Título: Re: Cambiar color JLabel en java
Publicado por: sapito169 en 12 Diciembre 2021, 06:05 AM
mmm estoy ocidado

Código (java) [Seleccionar]


package swing.comboexample;

import java.util.logging.Logger;

import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.Color;

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.text.AttributeSet.ColorAttribute;
public class HelloWorld extends JFrame{

   public static void main(String... args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> cboColor = new JComboBox<String>();
cboColor.addItem("rojo");
cboColor.addItem("verde");
cboColor.addItem("azul");
JLabel lblPrincipal = new JLabel("hola");
lblPrincipal.setOpaque(true);
cboColor.addActionListener(p->{
int index = cboColor.getSelectedIndex();

switch (index) {
case 1:
lblPrincipal.setBackground(Color.RED);
break;
case 2:
lblPrincipal.setBackground(Color.GREEN  );
break;

case 3:
lblPrincipal.setBackground(Color.BLUE);
break;

}
} );
helloWorld.getContentPane().setLayout( new FlowLayout() );
helloWorld.getContentPane().add(cboColor);

helloWorld.getContentPane().add(lblPrincipal);
helloWorld.setLocationRelativeTo(null);
helloWorld.pack();
helloWorld.setVisible(true);
}

       
}