Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all text in editable JComboBox and set cursor position

public class CursorAtStartFocusListener extends FocusAdapter {

@Override
public void focusGained(java.awt.event.FocusEvent evt) {
    Object source = evt.getSource();
    if (source instanceof JTextComponent) {
        JTextComponent comp = (JTextComponent) source;
        comp.setCaretPosition(0);
        comp.selectAll();
    } 
} }

jComboBox.getEditor().getEditorComponent().addFocusListener(new CursorAtStartFocusListener());

As you see from code above I want to select all text in editable JComboBox and set cursor position to the start. But I have problem if I first write comp.setCaretPosition(0) then comp.selectAll(), the text is selected but cursor is on the end of text, otherwise if I first write comp.selectAll() then comp.setCaretPosition(0), I get cursor in position that I want but text isn't selected. Have any idea how can I do this thing?

like image 898
Karen Avatar asked Mar 31 '12 14:03

Karen


1 Answers

Caret and selectAll is better to wrapping into invokeLater, but for JTextComponent (you can derive that from JComboBox too) you have to decide if you want to use

  • select all text == selectAll()

or use

  • select Caret (from Document)

EDIT

1) for editable JComboBox

Runnable doRun = new Runnable() {

    @Override
    public void run() {
        myComboBox.getEditor().setItem(0);
        myComboBox.getEditor().selectAll();
        myComboBox.requestFocus();
    }
};
SwingUtilities.invokeLater(doRun);

2) or derive JTextField or JFormattedTextField from editable JComboBox

((JTextField) myComboBox.getEditor().getEditorComponent())

then add FocusListener e.g.

    private FocusListener focsListener = new FocusListener() {

        @Override
        public void focusGained(FocusEvent e) {
            dumpInfo(e);
        }

        @Override
        public void focusLost(FocusEvent e) {
            //dumpInfo(e);
        }

        private void dumpInfo(FocusEvent e) {
            //System.out.println("Source  : " + name(e.getComponent()));
            //System.out.println("Opposite : " + name(e.getOppositeComponent()));
            //System.out.println("Temporary: " + e.isTemporary());
            final Component c = e.getComponent();
            if (c instanceof JFormattedTextField) {
                EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        ((JFormattedTextField) c).requestFocus();
                        ((JFormattedTextField) c).setText(((JFormattedTextField) c).getText());
                        ((JFormattedTextField) c).selectAll();
                    }
                });
            } else if (c instanceof JTextField) {
                EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        ((JTextField) c).requestFocus();
                        ((JTextField) c).setText(((JTextField) c).getText());
                        ((JTextField) c).selectAll();
                    }
                });
            }
        }

        private String name(Component c) {
            return (c == null) ? null : c.getName();
        }
    };

EDIT 2 :

SSCCE for editable JComboBox,

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.*;

public class ComboRendererTest {

    public ComboRendererTest() {
        JComboBox comboBox = new JComboBox();
        comboBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXX");
        comboBox.addItem(new Double(1));
        comboBox.addItem(new Double(2.25));
        comboBox.addItem(new Double(3.5));
        comboBox.setRenderer(new TwoDecimalRenderer(comboBox.getRenderer()));
        comboBox.setEditable(true);

        JComboBox comboBox1 = new JComboBox();
        comboBox1.setPrototypeDisplayValue("XXXXXXXXXXXXXXXX");
        comboBox1.addItem(new Double(1));
        comboBox1.addItem(new Double(2.25));
        comboBox1.addItem(new Double(3.5));
        comboBox1.setRenderer(new TwoDecimalRenderer(comboBox.getRenderer()));
        comboBox1.setEditable(true);

        JFrame frame = new JFrame();
        frame.add(comboBox, BorderLayout.NORTH);
        frame.add(comboBox1, BorderLayout.SOUTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                ComboRendererTest comboRendererTest = new ComboRendererTest();
            }
        });
    }
}

class TwoDecimalRenderer extends DefaultListCellRenderer {

    private ListCellRenderer defaultRenderer;

    public TwoDecimalRenderer(ListCellRenderer defaultRenderer) {
        this.defaultRenderer = defaultRenderer;
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        Component c = defaultRenderer.getListCellRendererComponent(
                list, value, index, isSelected, cellHasFocus);
        if (c instanceof JLabel) {
            c.setBackground(Color.red);
        } else {
            c.setBackground(Color.red);
            c = super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);
        }
        return c;
    }
}

EDIT 3.

dirty hack could be

JTextComponent editor = ((JTextField) myComboBox.getEditor().getEditorComponent());
editor.setCaretPosition(getLength());
editor.moveCaretPosition(0);
like image 68
mKorbel Avatar answered Oct 11 '22 09:10

mKorbel