0

I want to change my JLabel background to blue using mouseClicked. The name of my JLabel is lblKembali. I tried this code and when I tried to click the label it didnt change the background. Please help. Thank you.

lblKembali = new JLabel("Kembali");
lblKembali.setPreferredSize(new Dimension(400,30));
lblKembali.setMaximumSize(getPreferredSize());    
lblKembali.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                    lblKembali.setBackground(Color.BLUE);
            }
        });
Mei Lie
  • 91
  • 1
  • 11
  • Try making your `JLabel` opaque : `lblKembali.setOpaque(true)` – Arnaud Oct 26 '17 at 15:22
  • Possible duplicate of [How do I set a JLabel's background color?](https://stackoverflow.com/questions/2380314/how-do-i-set-a-jlabels-background-color) – Serr Oct 26 '17 at 15:25

1 Answers1

2

By default a JLabel is non-opaque so its background is not painted. You need to make the label opaque when you create it:

lblKembali = new JLabel("Kembali");
lblKembali.setOpaque( true );

Also you can make your listener more generic so it can be shared by multiple components by doing:

public void mouseClicked(MouseEvent e) 
{
    Component c = e.getComponent();
    c.setBackground(Color.BLUE);
}
camickr
  • 321,443
  • 19
  • 166
  • 288