How to position the cursor at the beginning of the field?

Asked

Viewed 1,175 times

2

How can I make a component (JTextField, JFormattedTextField and others) when being clicked/gaining focus, position the cursor in the position 0 component, especially when the component is already filled and the user clicks on it again? I am trying to use the setCaretPosition(0);

What I tried to:

package geral;

import java.awt.Dimension;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;

public class SetaPosicao extends JFrame implements FocusListener {

    private final JTextField campo = new JTextField();
    private final JFormattedTextField campo2 = new JFormattedTextField();

    public static void main(String[] args) {
        SetaPosicao tela = new SetaPosicao();
        tela.setVisible(true);
    }

    public SetaPosicao() {
        add(colocaCampo());
        setSize(500, 150);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        try {
            MaskFormatter mf = new MaskFormatter("#####-###");
            mf.install(campo2);
        } catch (Exception e) {

        }
    }

    private JComponent colocaCampo() {
        JPanel painel = new JPanel();
        JLabel label = new JLabel("TextField");
        JLabel label2 = new JLabel("Formatted");

        painel.add(label);
        painel.add(campo);
        campo.setPreferredSize(new Dimension(120, 22));
        //campo.setCaretPosition(0);

        painel.add(label2);
        painel.add(campo2);
        campo2.setPreferredSize(new Dimension(80, 22));
        //campo2.setCaretPosition(0);
        return painel;
    }

    @Override
    public void focusGained(FocusEvent e) {
        campo.setCaretPosition(0);
        campo2.setCaretPosition(0);
    }

    @Override
    public void focusLost(FocusEvent e) {
    }
}

2 answers

2


I believe the problem occurs because you are trying to change the position when the container of the fields gets focus, then when the text component gets focus with one click, the mouse will be positioned where it was clicked even.

One of the ways to solve it is by applying the focus event to the two text fields separately, and for that, you can create a class the part that extends from FocusAdapter and apply to both fields:

class CaretPosition extends FocusAdapter{

    @Override
    public void focusGained(FocusEvent e) {

        JTextComponent comp = (JTextComponent) e.getSource();           
        comp.setCaretPosition(0);
    }       
} 

Then just apply this class to the fields:

campo.addFocusListener(new CaretPosition());
campo2.addFocusListener(new CaretPosition());

Another problem I found in your code is the fact that you set the preferred size of the fields after adding them. I recommend that you define characteristics of all fields before adding them to containers.

The code with all the modifications is like this:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
import javax.swing.text.MaskFormatter;

public class SetaPosicao extends JFrame {

    private final JTextField campo = new JTextField();
    private final JFormattedTextField campo2 = new JFormattedTextField();

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            SetaPosicao tela = new SetaPosicao();
            tela.setVisible(true);
        });

    }

    public SetaPosicao() {
        add(colocaCampo());
        setSize(500, 150);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        try {
            MaskFormatter mf = new MaskFormatter("#####-###");
            mf.install(campo2);
        } catch (Exception e) {

        }
    }

    private JComponent colocaCampo() {

        JPanel painel = new JPanel();
        JLabel label = new JLabel("TextField");
        JLabel label2 = new JLabel("Formatted");

        campo.setPreferredSize(new Dimension(120, 22));

        campo.addFocusListener(new CaretPosition());
        campo2.addFocusListener(new CaretPosition());
        campo2.setPreferredSize(new Dimension(80, 22));

        painel.add(label);
        painel.add(campo);

        painel.add(label2);     
        painel.add(campo2);

        return painel;
    }

    class CaretPosition extends FocusAdapter{

        @Override
        public void focusGained(FocusEvent e) {

            JTextComponent comp = (JTextComponent) e.getSource();           
            comp.setCaretPosition(0);
        }       
    } 
}

It is never too much to inform also that swing applications should always be started within the specific thread for it, the EDT

  • what’s the difference between using Jcomponent and Jtextcomponent ? I can use in Jcomponent ?

  • 1

    @Java Jcomponent is the class that almost all swing components inherit, it is too Generic for the purpose of the question and lacks the method setcaretposition, After all, neither jpanel nor jlabel (which also inherit it) have text control such as jtextfield. Jtextcomponent is inherited by jtextfield and its subcomponents (such as jformatterdtextfield), and has text control methods for these fields, is the most recommended.

  • 1

    @Java not to mention that your Jcomponent is a container that you are adding a lot of fields, not just the two of text.

  • 1

    thank you, it was very clear !

-3

What I think you’re looking for is at the Click something like

controlo.requestFocus()

The control of setCaretPosition should automatically focus on index 0, but only after the requestFocus()

  • Just set the setcaretposition in a Focus system in the field. Doing so is kind of gambiarra and is not guaranteed to work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.