I would like to know the difference between requestFocusInWindow()
and grabFocus()
methods. Both of them work fine for grabbing the focus for me in this program. Therefore, i couldn't understand the difference.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Focus extends JFrame
{
JButton jb;
public Focus()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("grabFocus() vs requestFocusInWindow()");
setLayout(new FlowLayout());
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jb=new JButton("Open Dialog");
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
showDialog();
}
});
add(jb);
}
private void showDialog()
{
JDialog jd=new JDialog();
jd.setLayout(new GridLayout(2,2));
jd.setVisible(true);
JLabel l1=new JLabel("Label 1");
JLabel l2=new JLabel("Label 2");
JTextField jt1=new JTextField(20);
JTextField jt2=new JTextField(20);
jd.add(l1);
jd.add(jt1);
jd.add(l2);
jd.add(jt2);
// Both of them are doing the thing
//jt2.grabFocus();
jt2.requestFocus();
jd.pack();
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new Focus();
}
});
}
}
See Question&Answers more detail:os