aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes FocusListener problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "FocusListener problem" Watch "FocusListener problem" New topic
Author

FocusListener problem

Nich Aquilina
Greenhorn

Joined: Feb 05, 2007
Posts: 6
Hi, I have a problem using a focus listener, basically When a Jtext box looses focus I am only getting NULL. This is the chunk of code.. Is there any other property that I can use to identify the text box? I will be including ifs to work accordingly, but cannot seem to find anything on which value to get :/

static FocusListener fcListener = new FocusListener()
{
public void focusGained(FocusEvent e)
{
System.out.println(e.getComponent().getName());
}
public void focusLost(FocusEvent e)
{
System.out.println(e.getComponent().getName());
}
};


Thanks all, any help appreciated

Nich
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Have you tried e.getSource()?
Nich Aquilina
Greenhorn

Joined: Feb 05, 2007
Posts: 6
Hi Keith, Yes I did, and this is what returns with e.getSource()



javax.swing.JTextField[,152,17,152x17,layout=javax.swing.plaf.basic.BasicTextUI$
UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIReso
urce$CompoundBorderUIResource@1a125f0,flags=296,maximumSize=,minimumSize=,prefer
redSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextC
olor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=ja
vax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor
=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.
ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontalAl
ignment=LEADING]
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
You can use an instanceof test and then cast.
Nich Aquilina
Greenhorn

Joined: Feb 05, 2007
Posts: 6
You lost me here Keith. :/ Not sure where I should typecast at all
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
e.getSource() returns a reference of type Object that refers to the object that caused the event.

In your case, the source is a JTextField.

Since later you might add other components and use this FocusListener, you should test to see if e.getSource() is an instance of a JTextField, and if that is true, cast the reference to a JTextField reference, and then you can call methods on the reference.
[ March 05, 2007: Message edited by: Keith Lynn ]
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

A simple solution would be to call setName on the textbox when you create it. Then getName won't return null.


[My Blog]
All roads lead to JavaRanch
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: FocusListener problem