Re: Swing Text components
On Mar 28, 10:06 pm, "Uncle Sam" <sameervijay...@gmail.com> wrote:
...
...I tried to use the
Component.hasFocus() method on the text areas but the function always
returns false.
Seems to work just fine here*, I guess the
problem is in the code you did not show
us. In these situations, I suggest preparing
an SSCCE - that way, it is easy to see what
is going wrong.
For more details on the SSCCE, see..
<http://www.physci.org/codes/sscce.html>
* Example code..
<sscce>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class FocusLocation
extends JFrame
implements FocusListener {
JTextField field1 = new JTextField("Field 1");
JTextField field2 = new JTextField("Field 2");
JTextArea ta = new JTextArea( "Area 1",10,20);
FocusLocation() {
super("Focus Location");
Container c = getContentPane();
c.setLayout(new BorderLayout());
JPanel rhs = new JPanel(new BorderLayout());
JPanel textFields = new
JPanel(new GridLayout(0,1));
textFields.add(field1);
field1.addFocusListener(this);
textFields.add(field2);
field2.addFocusListener(this);
JSplitPane rhsSplit = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
new JLabel("Label 1"),
textFields
);
ta.addFocusListener(this);
JSplitPane sp1 = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
ta,
rhsSplit
);
c.add( sp1, BorderLayout.CENTER );
pack();
setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
setLocationRelativeTo(null);
}
public void focusLost(FocusEvent fe) {
}
public void focusGained(FocusEvent fe) {
Component c = fe.getComponent();
System.out.println(
c.getLocation() +
" has focus: " +
c.hasFocus());
examineFocus();
}
public void examineFocus() {
System.out.println( "Area 1: \t" +
ta.hasFocus() );
System.out.println( "Field 1: \t" +
field1.hasFocus() );
System.out.println( "Field 2: \t" +
field2.hasFocus() );
}
public static void main(String[] args) {
FocusLocation fl = new FocusLocation();
fl.setVisible( true );
}
}
</sscce>
Andrew T.