Java JComboBox set editor caret position

Description

Java JComboBox set editor caret position

import java.awt.FlowLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.text.JTextComponent;

class Demo extends JPanel {
  public Demo() {
    //  w  w  w  .j a v  a 2  s  .c o  m
    String options[] = { "CSS", "HTML", "Java", "Javascript" };
    setLayout(new FlowLayout());
    JComboBox<String> jcb = new JComboBox<String>(options);
    jcb.setEditable(true);
    add(jcb);
    setCaretPosition(jcb);
  }
  
  /**
   * When the text is longer than the text box it gets centered, this
   * method ensures they all show the end of the text, eg the filename.
   */
  public static void setCaretPosition(JComboBox comboBox) {
      Object item = comboBox.getSelectedItem();
      if (item != null) {
          String val = item.toString();
          JTextComponent c = (JTextComponent) comboBox.getEditor()
                  .getEditorComponent();
          c.setCaretPosition(val.length()-1);
      }
  }
}

public class Main {
  public static void main(String[] args) {
    Demo panel = new Demo();
    JFrame application = new JFrame();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    application.add(panel);
    application.setSize(250, 250);
    application.setVisible(true);
  }
}



PreviousNext

Related