Search code examples
javaswingnetbeansjlabel

how to set color of multiple jlabel on click netbeans?


I have multiple JLabels on a JPanel. When I click on JLabel the background changes to green.

I want to make only one label at a time green. For example, if I click on JLabel1 it has to turn green. If I click on another JLabel2, the JLabel1 must turn red and the JLabel2 must turn green.

I have a lot of JLabels and is non-productive to make an event for everyone. I searched a lot but I didn't find anything. I'm using Netbeans 8.1.

The JLabels are declared and initialized. This represents the room map of a hotel.

Declaration of JLabels :

 JLabel p401,p402,p403,phol,a301,a302,a303,a304,a305,a306,ahol;
 JLabel d201,d202,d203,d204,d205,d206,d207,d208,d209,d210,dhol;
 JLabel r10,r11,r12,r13,r14,r15,r16,r17,r18,r19;
 JLabel r20,r21,r22,r23,r24,r25,r26,r27,r28,r29;
 JLabel r30,r31,r32,r33,r34,r35,r36,r37,r38,r39;
 JLabel r40,r41,r42,r43,r44,r45,r46,r47,r48,r49;
 JLabel r50,r51,r52,r53,r54,r55,r56,r57,r58,r59;

Turn green function :

public void click(JLabel l)
{
    l.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            l.setOpaque(true);
            l.setBackground(Color.GREEN);
            System.out.println(l.getText());
            getCamId(l.getText()); 
            cam.setText(String.valueOf(idCam));
        }
    }); 
}

Solution

  • You could simply need to:

    1. Create 1 method which will handle what happens to a JLabel when clicked.
    2. Use the JPanel's .getComponents() to get all the components.
    3. Use the instance of operator to ensure that the component is a JLabel.
    4. If the component is a JLabel, assign the method in 1 as the click event handler.

    In the event handler, then, simply do the same as above. The event itself should give you access to the source, that is the component which triggered the event. You would simply need to do as follows:

    1. Iterate over the labels and set them to a green background.*
    2. Take the source of the event and set it to red.

    *This can be improved by keeping a label which denotes the currently selected label. When a label is clicked, you would reset the background of that label and update it to show the new label which the user has clicked.