4
I need that 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 extended and the beginning is omitted. The detail that is complicating the solution is that the component this disable
.
I used as a basis this other issue: How to set cursor at the beginning of the field?
However, in the question above, he does this through the event of gaining focus, 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);
}
}
}
Only one correction, the text field is not disabled, only it is not editable, are two very different situations.
– user28595