How to set contents in position 0 with field disabled?

4

I need, when my component receives a text (it will receive through a query), the text is "set" at the beginning of the field, because in many cases the text is long and the beginning is omitted. The detail that is complicating the solution is that the component is disable .

I used this other question as a basis: How to set cursor at startup of the field?

However, in the question above, it does this through the focus gain event, which will not be possible in my case.

Example:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JButton;

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

public class Position extends JFrame {

    private final JTextField campo = new JTextField();
    private JButton botao = new JButton("Clique");

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

    }

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

    private JComponent colocaCampo() {

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

        campo.setPreferredSize(new Dimension(120, 22));
        campo.addFocusListener(new CaretPosition());
        painel.add(label);
        painel.add(campo);
        campo.setEditable(false);

        painel.add(botao);
        botao.addActionListener((ActionEvent e) -> {
            campo.setText("Texto longo, realmente grande esse texto !");
        });
        botao.setPreferredSize(new Dimension(90, 22));
        return painel;
    }

    class CaretPosition extends FocusAdapter {

        @Override
        public void focusGained(FocusEvent e) {

            JTextComponent comp = (JTextComponent) e.getSource();
            comp.setCaretPosition(0);
        }
    }
}
    
asked by anonymous 25.08.2017 / 18:07

1 answer

5

In your own code is the solution, only placed in the wrong place. To define the position of the caret of a text component is through the setCaretPosition method, and if the text will be appended to the field via a button listener, then this method must be called after insertion of the text:

botao.addActionListener((ActionEvent e) -> {
    campo.setText("Texto longo, realmente grande esse texto !");
    campo.setCaretPosition(0);
});

Of course this is a simplistic solution, nothing prevents you from overwriting the setText method and forcing it into the initial position of the caret, but I believe this is an alternative that generates unnecessary complexity.

    
25.08.2017 / 19:10