选择可编辑JComboBox中的所有文本并设置光标位置

时间:2012-03-31 14:02:55

标签: java swing cursor jcombobox jtextfield

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(新   CursorAtStartFocusListener());

从上面的代码中可以看出,我想在可编辑的JComboBox中选择所有文本,并将光标位置设置为开头。 但是我有问题,如果我先写comp.setCaretPosition(0)然后comp.selectAll(),文本被选中但是光标在文本的末尾,否则如果我先写comp.selectAll()然后comp.setCaretPosition(0 ),我将光标放在我想要的位置但是没有选择文本。 知道我该怎么做这件事?

2 个答案:

答案 0 :(得分:5)

CaretselectAll最好包含在invokeLater中,但对于JTextComponent(您也可以从JComboBox推导出来),您必须决定是否你想用

  • 选择所有文字== selectAll()

或使用

  • 选择Caret(来自Document

修改

1)可编辑JComboBox

Runnable doRun = new Runnable() {

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

2)或从可编辑的JTextField

派生JFormattedTextFieldJComboBox
((JTextField) myComboBox.getEditor().getEditorComponent())

然后添加FocusListener,例如

    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();
        }
    };

编辑2:

SSCCE用于可编辑的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;
    }
}

编辑3。

脏黑客可能

JTextComponent editor = ((JTextField) myComboBox.getEditor().getEditorComponent());
editor.setCaretPosition(getLength());
editor.moveCaretPosition(0);

答案 1 :(得分:0)

尝试一下...

                JTextComponent comp = (JTextComponent) source;
                comp.setCaretPosition(comp.getText().length());
                comp.moveCaretPosition(0);