4

in my application i get a component to focus , it could be a jpanel , and is could be a jbutton or a user custom made component

how can i know when to call transferFosus ,and when to call requestFocus

thanks you

shay
  • 1,317
  • 4
  • 23
  • 35
  • the code to request focus , should know what method to call it can be a JPanel with some buttons inside (transferFocus) or just a JButton (requestFocusInWindow) what method should i call when i know i get a JComponenet – shay Apr 26 '10 at 16:49
  • what i did for now was if(dCompoenet instanceof AbstractButton){ dCompoenet.requestFocusInWindow(); }else{ dCompoenet.transferFocus(); } what do u think ? – shay Apr 27 '10 at 10:32

3 Answers3

3

transferFocus() sends focus to the next component. Also note that transferFocus() will always transfer the focus in the forward direction.

requestFocus() sends focus to calling component. However, there is no guarantee that this will be successful. Focus behavior is platform-dependent to certain extend.

The recommended mentod for gaining focus is to use requestFocusInWindow(). Refer to this post - might come very handy in playing with focus.

Community
  • 1
  • 1
ring bearer
  • 20,383
  • 7
  • 59
  • 72
  • so i get a jcompoenent and i need to deside what to call transferFocus or requestFocusInWindow i know i will cal 'requestFocusInWindow' for a jbutton and 'transferFocus' for a jpanel that holds buttons inside it by what i can decide what method to call – shay Apr 26 '10 at 22:39
1

Use transferFocus() when you want to advance focus according to the focus order. requestFocus() is used to explicitly set the focus to a component.

Some background reading in Focus on Swing

objects
  • 8,637
  • 4
  • 30
  • 38
0

It's rare that you would need to call either since its usually appropriate to let the user's keyboard/mouse actions determine focus. But transferFocus send focus away from your component and requestFocus brings focus to your component.

staticman
  • 728
  • 5
  • 9