Java Swing How to - Add JScrollPane on JComboBox Editor








Question

We would like to know how to add JScrollPane on JComboBox Editor.

Answer

import java.awt.Component;
import java.awt.Dimension;
/*from   w w w .j  ava  2 s.  c o m*/
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.plaf.basic.BasicComboBoxEditor;

public class Main {

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    JComboBox combobox = new JComboBox();

    combobox.addItem("Item1");
    combobox
        .addItem("Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2 Item2");
    combobox.addItem("Item3");

    combobox.setEditor(new MyEditor());
    combobox.setEditable(true);

    combobox.setPreferredSize(new Dimension(200, 50));
    frame.add(combobox);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

}

class MyEditor extends BasicComboBoxEditor {
  JScrollPane scroller = new JScrollPane();
  public MyEditor() {
    super();
    scroller.setViewportView(editor);
    scroller
        .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  }
  @Override
  public Component getEditorComponent() {
    return scroller;
  }

  @Override
  protected JTextField createEditorComponent() {
    JTextField editor = new JTextField();

    return editor;
  }
}