Change Background Color of a JLabel by pressing a JButton from another window

2

I would like to know how to change the background color (setBackground) of a JLabel by pressing a button from another window.

(JLabel in class Window1)

lblLuzC = new JLabel("");
lblLuzC.setOpaque(true);
lblLuzC.setBackground(Color.RED);
lblLuzC.setBounds(204, 224, 16, 16);
contentPane.add(lblLuzC);

(JButton in class Ventana2)

btnColor = new JButton("Cambiar color");
btnColor.setBounds(144, 85, 95, 23);
contentPane.add(btnColor);
btnColor.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

});
    
asked by JHG 25.05.2018 в 02:17
source

2 answers

1

The first thing you can do is create an object of the class Ventana1:

Ventana1 objetoVentana1 = new Ventana1();

So that you can access the methods and properties of that class.

After the action of the button, in ActionListener() , would be something like this:

btnColor.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       objetoVentana1.lblLuzC.setBackground(Color.BLUE);
});

I realized that the name of your button when you put the ActionListener() you have put 2 times btn, sure it was a mistake when copying. Greetings

    
answered by 25.05.2018 / 08:58
source
1

Generate JLabel getter (window1). Access the JLabel in window2 using the said method.

   btnColor.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
          objetoVentana1.getLblLuzC.setBackground(Color.BLUE);
          objetoVentana1.setVisible(true);

   });
    
answered by 25.05.2018 в 11:21