0

I have 7 Jlabels in my JFrame and I want achieve clicking on 1 JLabel setting the background to black and the text colour to white while leaving the other Jlabels backgrounds white and black text with as minimal code possible. I managed to do it but the result was chunks of code for each Mouse Click event.

Example of my attempt:

private void Label1MouseClicked(java.awt.event.MouseEvent evt) {    

    //Highlighted

    Label1.setBackground(new java.awt.Color(0, 0, 0, 255));
    Label1.setForeground(new java.awt.Color(255, 255, 255, 255));

    //Other Jlabels background and colour resetting

    Label2.setBackground(new java.awt.Color(255, 255, 255, 255));
    Label2.setForeground(new java.awt.Color(0, 0, 0, 255));
    Label3.setBackground(new java.awt.Color(255, 255, 255, 255));
    Label3.setForeground(new java.awt.Color(0, 0, 0, 255));
    Label4.setBackground(new java.awt.Color(255, 255, 255, 255));
    Label4.setForeground(new java.awt.Color(0, 0, 0, 255));
    Label5.setBackground(new java.awt.Color(255, 255, 255, 255));
    Label5.setForeground(new java.awt.Color(0, 0, 0, 255));
    Label6.setBackground(new java.awt.Color(255, 255, 255, 255));
    Label6.setForeground(new java.awt.Color(0, 0, 0, 255));
    Label7.setBackground(new java.awt.Color(255, 255, 255, 255));
    Label7.setForeground(new java.awt.Color(0, 0, 0, 255));

} 

I entered that code for each JLabel mouse click event making the highlighted label have a black background and white text.

How can I shorten this code?

Thanks in advance.

Matt J
  • 99
  • 2
  • 12

1 Answers1

0

create a lable array

JLabel labels[] = new JLabel[6];

and initialize lables and add to container

lables[0]=new JLabel("lable 1");

then use a loop for set colors

for(int i=0;i<lables.lenght;i++){
   lables[i].setBackground(new java.awt.Color(0, 0, 0, 255));
   lables[i].setForeground(new java.awt.Color(255, 255, 255, 255));
}

you can also import Color class

 import java.awt.Color; 

then you can use

lables[i].setBackground(Color.white);
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60