I want my jLabel component to have a different background colour when clicked. I have actually written my code for the background colour to change but I need it to retain the new colour after the click and go back to default on a second click. I need help on this.
private void jLabel1MouseEntered(java.awt.event.MouseEvent evt) {
jLabel1.setOpaque(true);
jLabel1.setBackground(Color.orange);
}
private void jLabel1MouseExited(java.awt.event.MouseEvent evt) {
jLabel1.setBackground(Color.white);
jLabel1.setOpaque(false);
}
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {
jLabel1.setBackground(Color.green);
}
You should put the command in Mouse Clicked or pressed event
and you need to set the JLable setOpaque
to true
otherwise the background is not going to be painted because the default of opaque
is false
for JLabel
.
ie
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {
jLabel1.setOpaque(true);
jLabel1.setBackground(Color.red);
}
You should make a boolean that stores the state of the button
boolean isClicked = false;
And then in your action listener, check it's value, update the labels then make it the opposite of what it was
if(isClicked)
{
label.setBackground(Color.BLUE);
isClicked = false;
}
else
{
label.setBackground(Color.GRAY);
isClicked = true;
}
How do I retain the new background colour of a jlabel after it has been clicked and to make it go back to default on a second click?
There are many ways to do it, but the ultimate concept is similar. You just need to keep a record of the new background colour in a variable.
In this case, I used 2 variables to retain the colour oldColor
and newColor
.
class MainPanel extends JPanel{ //Not necessary must be a JPanel. For e.g. only
private Color oldColor;
private Color newColor;
private JLabel lbl;
private JButton btn;
//Constructors, initializations, getters, setters not shown
public void init(){
lbl.setOpaque(true);
btn = new JButton("Click to switch color");
btn.addActionListener(new ButtonHandler());
oldColor = lbl.getBackground(); //can be any color you want
newColor = Color.GREEN; //can be any color you want
}
private class ButtonHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvet e){
if(lbl.getBackground().equals(oldColor))
lbl.setBackground(newColor);
else
lbl.setBackground(oldColor);
}
}
}
If you have more colours, you can always use an array, an ArrayList or any other data structure which is suitable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.