Java Swing How to - Right align JComboBox








Question

We would like to know how to right align JComboBox.

Answer

//from  w  w  w .  j a  v a 2s .c o  m
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {

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

    ((JLabel) comboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);

    comboBox.addItem("Apple");
    comboBox.addItem("Orange");
    comboBox.addItem("Mango");

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

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