Re: Auto Select text on textfield focus




andrewthommo@xxxxxxxxx wrote:
therodet@xxxxxxxxx wrote:
I want to make JTextFields in my application automatically select all
text when they receive focus, whether by mouse or by keyboard. More
importantly, I don't want to have to manually install listeners on
every JTextField I create.

Here's one way, try this for a few laughs..

<sscce>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class AutoSelectTextField
extends JTextField
implements FocusListener {

AutoSelectTextField(String text) {
super(text);
addFocusListener(this);
}

public void focusLost(FocusEvent fe) {}
public void focusGained(FocusEvent fe) {
setCaretPosition(0);
if (getText()!=null) {
moveCaretPosition( getText().length() );
}
}

public static void main(String[] args) {
JFrame f = new JFrame();
Container c = f.getContentPane();
c.setLayout(new GridLayout(0,1));
StringBuffer sb = new StringBuffer();
for (int ii=0; ii<10; ii++) {
c.add( new AutoSelectTextField(sb.toString()) );
sb.append("Ha ");
}
f.pack();
f.setVisible(true);
}
}
</sscce>

HTH

Andrew T.

I had considered that option, but that would require altering quite a
few classes that alreay have JTextFields and JFormattedTextFields,
which I would prefer to avoid.

.



Relevant Pages

  • revise my code
    ... public static void main (String[] args) ... public void actionPerformed ... public class Form1 extends JFrame implements ActionListener ... JTextField text1; ...
    (comp.lang.java.programmer)
  • revise this code
    ... public static void main (String[] args) ... public void actionPerformed ... public class Form1 extends JFrame implements ActionListener ... JTextField text1; ...
    (comp.lang.java.programmer)
  • Re: Auto Select text on textfield focus
    ... whether by mouse or by keyboard. ... I don't want to have to manually install listeners on ... every JTextField I create. ... public void focusGained{ ...
    (comp.lang.java.gui)
  • Re: Creating a simple visual user interface
    ... public void actionPerformed{ ... // put it in the JTextField ... String str = tf.getText.toUpperCase; ... Posted via NewsDemon.com - Premium Uncensored Newsgroup Service ...
    (comp.lang.java.programmer)
  • JButton questions
    ... JTextField tfTitle = new JTextField; ... public void actionPerformed{ ... DVD dvd = dvds.get); ... String title; ...
    (comp.lang.java.help)