Question

I have 5 JTextFields in a JFrame and I have added a FocusListener to all of them in a loop.

On focusGained() event, I'm moving the caret to the end of the JTextField using setCaretPosition() method.

On focusLost() event, I'm trying to move the caret to the beginning of the JTextField so that the text inside the respective field can be read from the beginning.

I can't figure out what to do in the focusLost event. I tried setting the caretPosition to zero but it didn't work.

Could someone help me out here?

Edit:

Here's the SSCCE:

public void focusGained(FocusEvent etffl)
{
 for(int i = 0; i < 5; i++)
 {
  field[i].setCaretPosition(field[i].getText().length());
 }
}
public void focusLost(FocusEvent etffl)
{
 for(int i = 0; i < 5; i++)
 {
  field[i].setCaretPosition(0);
 }
}

Edit #2:

Here's the MCTRE:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

    class SampleGUI

    {
     public static JTextField[] field = new JTextField[5];
     public static void main(String[] args)

     {
      JFrame frame = new JFrame("Frame");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      final JPanel panel = new JPanel();

      for(int i=0; i<5; i++)
      {
       field[i] = new JTextField(20);
       field[i].addFocusListener(new TextFieldFocusListener());
       panel.add(field[i]);
      }

      frame.add(panel);
      frame.setSize(300,300);
      frame.setVisible(true);

     }

    }

    //TextFieldFocusListener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class TextFieldFocusListener implements FocusListener

{

 public void focusGained(FocusEvent etffl)
 {
  for(int i = 0; i < 5; i++)
  {
   SampleGUI.field[i].setCaretPosition(SampleGUI.field[i].getText().length());
  }
 }
 public void focusLost(FocusEvent etffl)
 {
  for(int i = 0; i < 5; i++)
  {
   SampleGUI.field[i].setCaretPosition(0);
  }
 }
}
Was it helpful?

Solution

I tried setting the caretPosition to zero but it didn't work.

Try wrapping the code in a SwingUtilities.invokeLater().

If you need more help then post a MCTRE that demonstrates the problem.

Your code is overly complicated. You only need to reset the caret for the text field that generated the event (not all of the text fields):

class TextFieldFocusListener implements FocusListener
{
    public void focusGained(FocusEvent etffl)
    {
        JTextField textField = (JTextField)etffl.getComponent();
        textField.setCaretPosition(textField.getDocument().getLength());
    }

    public void focusLost(FocusEvent etffl)
    {
        JTextField textField = (JTextField)etffl.getComponent();
        textField.setCaretPosition(0);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top