How to right align the text in a ComboBox in Java


To right align the text in a JComboBox, use the following:

ComponentOrientation.RIGHT_TO_LEFT

The following is an example to right align the text in a ComboBox:

Example

import java.awt.Component;
import java.awt.ComponentOrientation;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
public class SwingDemo extends JFrame {
   public SwingDemo() {
      JComboBox<String> combo = new JComboBox<String>();
      combo.setRenderer(new MyListCellRenderer());
      combo.addItem("One");
      combo.addItem("Two");
      combo.addItem("Three");
      combo.addItem("Four");
      combo.addItem("Five");
      getContentPane().add(combo, "North");
      setSize(600, 400);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
   }
   public static void main(String[] args) {
      new SwingDemo().setVisible(true);
   }
}
class MyListCellRenderer extends DefaultListCellRenderer {
   @Override
   public Component getListCellRendererComponent(
      JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
      c.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      return c;
   }
}

Output

Updated on: 30-Jul-2019

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements