• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to use method requestFocus()

 
Tom John
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a very simple program to test use method requestFocus()
my program is below:
////////////////////////////////////////////////////
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class TextTestFrame extends JFrame implements FocusListener
{ public TextTestFrame()
{ setTitle("TextTest");
setSize(300, 200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
//addFocusEvent(this);
addFocusListener(this);

Container contentPane = getContentPane();
JPanel p = new JPanel();
hourField = new JTextField("12", 3);
p.add(hourField);
minuteField = new JTextField("00", 3);
//minuteField.requestFocus();
p.add(minuteField);
contentPane.add(p, "South");
}
public void focusLost(FocusEvent evt)
{
}
public void focusGained(FocusEvent evt)
{
minuteField.requestFocus();
}
private JTextField hourField;
private JTextField minuteField;
}
public class TextTest
{ public static void main(String[] args)
{ JFrame frame = new TextTestFrame();
frame.show();
}
}
//////////////////////////////
I only want when I run this program , the focus at minuteField . but it always focus at hourField .
What’s wrong with me ? how to do it ?
Please answer my question detailly!
Thanx!
 
Dirk Mohr
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, look at this:

1. If you dont�t want to handel FocusEvents you don�t need a FocusListener.
2. The requestFocus() method must be called after the frame is set visible.
Regards, Dirk
PS: No offence, the way you format your code - it�s sort of weird.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!