Skip to main content

MouseClick on JLabel

33 replies [Last post]
javaswingus
Offline
Joined: 2006-02-17

I have two JLabels in a JPanel. When I click on a JLabel, I set border for it
but when I click on another label, the border is painted for that label too. What I need is when I click on the 2nd label, the border should be set null for the 1st label. How to do it?

public void mouseClicked(MouseEvent me)
{
if(me.getClickCount() == 1)
{
label.setBorder(new LineBorder(Color.blue));
//label.getText().setBorder(..);
}
}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
javaswingus
Offline
Joined: 2006-02-17

vivaran,
Thanks a lot for your help. The code cleared my doubts.

Thanks

viravan
Offline
Joined: 2003-06-23

> vivaran,
> Thanks a lot for your help. The code cleared my
> doubts.

You're welcomed! Looks like you've picked quite a few brains on this subject ( http://forum.java.sun.com/thread.jsp?forum=57&thread=415947 )...

;o)

V.V.

javaswingus
Offline
Joined: 2006-02-17

viravan,
Yes, but the solution has given me some sort of ideas on JLabel and Keybindings. :)

Thanks for help anyway.

srotman
Offline
Joined: 2003-06-16

hmm.. sorry, had a double post here...

Message was edited by: srotman

viravan
Offline
Joined: 2003-06-23

>little question vira:
>
>why do u want to extend the JLabel, only to call the addMouseListener method. >Why not just calling it from outside?

The OP doesn't want to have to add a separate listener to every label (and there apparently will be a lot of them). This way, the OP wouldn't have to be bothered with it (granted, there will still be as many listeners out there as there are labels).

;o)

V.V.

srotman
Offline
Joined: 2003-06-16

> The OP doesn't want to have to add a separate
> listener to every label (and there apparently will be
> a lot of them).
> This way, the OP wouldn't have to be
> bothered with it (granted, there will still be as
> many listeners out there as there are labels).

If you add the listener from the outside the way I just showed, you will only have to create one (1!!) listener, and can add this listener to every label.
So you won't have to add a separate listener to every label, cause you add the same listener to every label.
Also, you don't have as many listeners as labels that way.

viravan
Offline
Joined: 2003-06-23

>If you add the listener from the outside the way I just showed, you will only have to create one (1!!) listener

Why don't you edit the code that I posted to show the OP your proposed solution because I'm a little hazy on what you said above (i.e., I don't see how you can have only one listener for all labels)?

;o)

V.V.

srotman
Offline
Joined: 2003-06-16

> Why don't you edit the code that I posted to show the
> OP your proposed solution

Well, javaswingus told us a few posts ago he (or she) is not looking for code, just logic.
I really think by now he should have all the logic he needs. Looking at vdkuils earlier posts, your post, and mine, and combine one thing with another will definitely get to the right solution..
Maybe he can share with us if he found the solution already?

After all, it really is better to [b]help[/b] one find a solution than just [b]give[/b] it. If you find the solution yourself it will be much harder to forget it again ;).

viravan
Offline
Joined: 2003-06-23

>If you find the solution yourself it will be much harder to forget it again

At my age, I don't even remember what I had for breakfast...LOL

;o)

V.V.

zander
Offline
Joined: 2003-06-13

> >If you find the solution yourself it will be much
> harder to forget it again
>
> At my age, I don't even remember what I had for
> breakfast...LOL

That has nothing to do with age; thats a 'dusty professor' problem!

But as we are on the topic of the more personal stuff; could you please tell me what that 'rednose' smily is that you have at every post? Just curious :)

viravan
Offline
Joined: 2003-06-23

>That has nothing to do with age; thats a 'dusty professor' problem!

Well.... when you sink your teeth into a thick juicy steak and they just stay there, I'll say it has everything to do with age....LOL.

>what that 'rednose' smily

Don't know what you're talking about..... the semicolon, little o and close paren are sort of a signature of my post in the JDC forums for the past few years and I just continued the tradition. The jive forum must have converted it to an icon for other people to see but all I see in my own post is just the three characters that I used.

;o)

V.V.

srotman
Offline
Joined: 2003-06-16

javaswingus, it looks a [b]lot[/b] nicer if you put code tags around your code.
as in ( [ code ] at the start of your code, and [ /code ] at the end of your code, but without the spaces inside the brackets)

Anonymous

> Mamoulian,
> Thanks for the reply. It works but that is not the
> way to do. What if there are 10 or 20 labels placed
> on the JPanel? Will you write 10 or 20
> MouseListeners? There should be a way for it.

Oh you are right, I haven't thought on multiple JLabels, just of this two. As said, I am no expert in Swing but willing to learn ;) The MouseListener classes is the way as JBuilder 8 generates the listeners. I hoped to get some response from Swing experts here what to do or what is the best solution :)

Anyone out there?

Anonymous

You could do it this way:

[code]
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class LabelTest extends JFrame {
JPanel panel = new JPanel();
JLabel leftlabel = new JLabel("left");
JLabel rightlabel = new JLabel("right");

LineBorder blueborder = new LineBorder(Color.blue);

public static void main(String[] args) {
LabelTest test = new LabelTest();
test.init();
test.show();
}

void init() {
Container cp = getContentPane();
cp.add(panel);
panel.setLayout(new BorderLayout());
panel.add(leftlabel, BorderLayout.WEST);
panel.add(rightlabel, BorderLayout.EAST);
leftlabel.addMouseListener(new LeftLabelMouseAdapter(this));
rightlabel.addMouseListener(new RightLabelMouseAdapter(this));
}
}

class LeftLabelMouseAdapter extends MouseAdapter {
private LabelTest lt;

public LeftLabelMouseAdapter(LabelTest lt) {
this.lt = lt;
}
public void mouseClicked(MouseEvent evt) {
if(evt.getClickCount() == 1) {
lt.leftlabel.setBorder(lt.blueborder);
}
}
}

class RightLabelMouseAdapter extends MouseAdapter {
private LabelTest lt;

public RightLabelMouseAdapter(LabelTest lt) {
this.lt = lt;
}

public void mouseClicked(MouseEvent evt) {
if(evt.getClickCount() == 1) {
lt.leftlabel.setBorder(null);
}
}
}
[/code]

I am using two MouseListeners, one for the left label and one for the right. I am by for no Swing expert, what about other possibilities? Is there a way to make it much better?

javaswingus
Offline
Joined: 2006-02-17

Mamoulian,
Thanks for the reply. It works but that is not the way to do. What if there are 10 or 20 labels placed on the JPanel? Will you write 10 or 20 MouseListeners? There should be a way for it.

Any one who knows the answer?

Thanks

vdkuil
Offline
Joined: 2006-02-17

mousevent.getSource is the JLabel...

maybe that helps?

javaswingus
Offline
Joined: 2006-02-17

vdkuil,
Thanks for the reply. getSource() == label works similar to the earliar reply post. Because I dont know how many labels will be present in the Panel, they are added dynamically through drag and drop. So, how can you tell which label has been clicked?

let us say that we can add it through getSource() instanceof JLabel, then when I click on 1,2,3,etc.. labels, all of them will look selected. That is not what I need. When the mouse is clied on the second label it should get border painted and if the 1st label is clicked, the second label border sould be removed and the border should be set for the 1st label.

Any one having an idea?

vdkuil
Offline
Joined: 2006-02-17

>> vdkuil,
>> Thanks for the reply. getSource() == label works
>> similar to the earliar reply post.
well no, since you can have one mouselistener instead of x....

>> what I need. When the mouse is clied on the second
>> label it should get border painted and if the 1st
>> label is clicked, the second label border sould be
>> removed and the border should be set for the 1st
>> label.
>Any one having an idea?
wel what about panel.getComponents()
if (getComponentAt(i) != mouseEvent.getSource()
removeLabel()

any other solution will be too obvious.. (like keeping a reference to the last label????) ;)

javaswingus
Offline
Joined: 2006-02-17

Hello,
Based on your input I changed my code so

[code]
public void mouseClicked(MouseEvent me)
{
//System.out.println("label clicked"+label.getID());
Point p = label.getCenter();
System.out.println("point:"+p);
//selectedLabel = (JLabel)label.getComponentAt(p);
getComponents();
label.lbl_slct = (JComponent)getComponentAt(p);
if(me.getSource() == label)
{
label.setBorder(new LineBorder(Color.blue));
}
if(getComponentAt(p) != me.getSource())
{
label.setBorder(null);
}
}

But still it is not working. My class is extending JPanel and the main file is an applet.
Any help?
[/code]

Message was edited by: jeff (added code tag)

vdkuil
Offline
Joined: 2006-02-17

> Hello,
> Based on your input I changed my code so
> public void mouseClicked(MouseEvent me)
> {
> //System.out.println("label
> el clicked"+label.getID());
> Point p = label.getCenter();
> System.out.println("point:"+p);
> //selectedLabel =
> = (JLabel)label.getComponentAt(p);
> getComponents();
> label.lbl_slct = (JComponent)getComponentAt(p);
> if(me.getSource() == label)
> {
> label.setBorder(new LineBorder(Color.blue));
> }
> if(getComponentAt(p) != me.getSource())
> {
> label.setBorder(null);
> }
> }
>
> But still it is not working. My class is extending
> JPanel and the main file is an applet.

Seems you've been a little too overactive.. ;)

If you replace getComponentAt(point) with getComponent(index) that should work... (for loop over getComponents().size.... or something like that...
getComponentAt(mouseEvent.getPoint()) gives you that same component as mouseEvent.getSource()

javaswingus
Offline
Joined: 2006-02-17

I will try and get back to you

viravan
Offline
Joined: 2003-06-23

The easiest thing I can think of is to subclass JLabel, add a focus listner to the subclass such that when focus is gained, you set the border, when focus is lost, you remove the border.

;o)

V.V.

zander
Offline
Joined: 2003-06-13

> The easiest thing I can think of is to subclass
> JLabel, add a focus listner to the subclass such that
> when focus is gained, you set the border, when focus
> is lost, you remove the border.

IIRC, the label does not get focus events since it does not get focus.

javaswingus
Offline
Joined: 2006-02-17

Yes,
You cannot have a focus listener on a Label and I tried to have Keybinding to it and failed. So, Waste of time discussing on this topic. Sorry :((

zander
Offline
Joined: 2003-06-13

So, javaSwingus; did you get a working application yet? I believe the hints vdKuil gave should be enough to get you rolling; was it?
Let us know where you got stuck.

javaswingus
Offline
Joined: 2006-02-17

zander,
Well, Can I have focus on JLabel? If so, then I can be able to achieve what I am looking for. Say, 10 labels in JPanel, only one of them will have a focus when clicked on it for a single time i.e me.getClickCount == 1. To show that it has focus, just add a border to it.

One more question not related to this topic is.

I have 10 labels, I am giving them titles as JPanel.getComponentCount() so, the first label in the panel will be label+0, second label+1,etc..
I am deleting one of the label say label+8, so now the question is when I try to add a new label to the panel again, the last added label will have label+10.

There will be two label+10 now, as the componentcount after delete is only 9. What I need is when I add a new label again after 10, it should be 11, or 12,etc..

Can you help?

Thanks

zander
Offline
Joined: 2003-06-13

> zander,
> Well, Can I have focus on JLabel?
No, and I told you so before.
This is also not what vdkuil suggested.

So I repeat my question; the application you started to work on based on the hints provided; where did they fail?
I'm not going to give you an application, you still have to do that yourself. But when you can't give feedback on what is going wrong, we can't help you.

> One more question not related to this topic is.
>
> I have 10 labels, I am giving them titles as
> JPanel.getComponentCount() so, the first label in the
> panel will be label+0, second label+1,etc..
> I am deleting one of the label say label+8, so now
> the question is when I try to add a new label to the
> panel again, the last added label will have label+10.

Why would you want to do it like that?
Just take a step back for a moment and think why you are doing that. You are thinking far too complex.
Maybe its good to pick up an object-orientation course and follow that first, the thing you apparently missded is the concept of member variables.

Good luck!

javaswingus
Offline
Joined: 2006-02-17

zander,
There is a reason for why I am doing my Label count so. I have saving and editing of my applications. What you meant is to put a int count and increment it, is it?

This is not going to work for me. Because the application may be saved after adding 10 labels to panel and then reopened tomorrow, then what is the int value? 0, so again labels are added from first. Problems here!!

A label cannot have a focus and that is the reason why I was asking you the question again to see if there is an alternative solution. I am not asking for code, just logic.

viravan
Offline
Joined: 2003-06-23

>A label cannot have a focus

JLabel inherits the [b]addFocusListener[/b] from java.awt.Component......so, there must be a way to do it (see comments from the source code shown below)

/**
* A display area for a short text string or an image,
* or both.
* A label does not react to input events.
* As a result, it cannot get the keyboard focus.
* A label can, however, display a keyboard alternative
* as a convenience for a nearby component
* that has a keyboard alternative but can't display it.
...

;o)

V.V.

srotman
Offline
Joined: 2003-06-16

U can add a FocusListener, but IT'S NO USE!! the label just does not aquire focus, so you can listen all you want, but you'll never hear a thing!!

This is mentioned a severall times before in this thread..

viravan
Offline
Joined: 2003-06-23

>This is mentioned a severall times before in this thread..

Hmmmmmmmm, I know you and Zander do a lot of work with UI but just out of curiosity, I'll give it a whack and see... In the mean time, the OP can always subclass JLabel and implements MouseListener!

;o)

V.V.

viravan
Offline
Joined: 2003-06-23

Ok, I see what happens.... under certainc circumstances, JLabel will requestFocus for itself but it doesn't notify anybody else. Anyway, here is a solution to your problem:

[pre]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class LabelTest extends JFrame {
public myJLabel currentLabel=null;
public static void main(String[] args) {
new LabelTest();
}

LabelTest() {
Container cp = getContentPane();
cp.setLayout(new BorderLayout(5,5));
myJLabel leftlabel = new myJLabel("left",this);
cp.add("West",leftlabel);
myJLabel rightlabel = new myJLabel("right",this);
cp.add("East",rightlabel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,100);
setVisible(true);
}
}

class myJLabel extends JLabel {
LineBorder blueborder = new LineBorder(Color.blue);
myJLabel(String text, final LabelTest frame) {
super(text);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (frame.currentLabel!=null) frame.currentLabel.setBorder(null);
setBorder(blueborder);
frame.currentLabel=(myJLabel)evt.getSource();
}
});
}
}
[/pre]

If you want to save the state of the last clicked label, you'll have to save [b]currentLabel[/b].

;o)

V.V.

srotman
Offline
Joined: 2003-06-16

little question vira:

why do u want to extend the JLabel, only to call the addMouseListener method. Why not just calling it from outside?

so instead of [code]
public MyLabel extends JLabel {
MyLabel( ... ) {
...
addMouseListener( ... );
}
}[/code]

just call [code]
JLabel bla = new JLabel ( ... );
bla.addMouseListener( ... );[/code]