Java Swing How to - Right align the text in a JCombobox








Question

We would like to know how to right align the text in a JCombobox.

Answer

import java.awt.Component;
import java.awt.ComponentOrientation;
/*w  w w . j a va  2 s. c  om*/
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;

public class Main extends JFrame {
  public Main() {
    JComboBox<String> comboBox = new JComboBox<String>();
    comboBox.setRenderer(new MyListCellRenderer());
    comboBox.addItem("Hi");
    comboBox.addItem("Hello");
    comboBox.addItem("How are you?");

    getContentPane().add(comboBox, "North");
    setSize(400, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

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

class MyListCellRenderer extends DefaultListCellRenderer {
  @Override
  public Component getListCellRendererComponent(JList list, Object value,
      int index, boolean isSelected, boolean cellHasFocus) {
    Component component = super.getListCellRendererComponent(list, value,
        index, isSelected, cellHasFocus);
    component.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    return component;
  }
}