1

I was trying to paint border around JLabel when it is clicked. Just like JButtons are painted.

I thought it would be easy but I failed to do the job.

I tried to figure out what happens to JButtons when clicked by putting breakpoints in source codes. But I got lost, however, I have a feeling that javax.swing.plaf and its subpackages are what I need.

Am I right? Is there a simpler way to do the job.

Here is an example:

Example

tenorsax
  • 21,123
  • 9
  • 60
  • 107
Mohayemin
  • 3,841
  • 4
  • 25
  • 54

1 Answers1

1

You could add MouseListener to your label and setup a border in mousePressed/mouseReleased methods. Here is a simplified example:

    label.addMouseListener(new MouseAdapter(){
        @Override
        public void mousePressed(MouseEvent arg0) {
            label.setBorder(BorderFactory.createLineBorder(Color.black));
        }
        @Override
        public void mouseReleased(MouseEvent arg0) {
            label.setBorder(null);
        }
    });

Also, as an alternative you can make a button with a flat style that will look like a label. This answer can be useful.

Community
  • 1
  • 1
tenorsax
  • 21,123
  • 9
  • 60
  • 107