Java Swing How to - Right align JComboBox with Renderer








Question

We would like to know how to right align JComboBox with Renderer.

Answer

import java.awt.Component;
import java.awt.ComponentOrientation;
/*w w w  .  java  2  s .  c  o  m*/
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

public class Main extends JFrame {

  public Main() {
    JComboBox comboBox = new JComboBox();

    setListCellRendererOf(comboBox);

    comboBox.addItem("A");
    comboBox.addItem("B");
    comboBox.addItem("C");

    getContentPane().add(comboBox, "North");
    setSize(200, 100);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

  private void setListCellRendererOf(JComboBox comboBox) {
    comboBox.setRenderer(new ListCellRenderer() {
      @Override
      public Component getListCellRendererComponent(JList list, Object value,
          int index, boolean isSelected, boolean cellHasFocus) {

        Component component = new DefaultListCellRenderer()
            .getListCellRendererComponent(list, value, index, isSelected,
                cellHasFocus);

        component.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        return component;
      }
    });
  }

  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}